面向对象

类方法与静态方法

类方法:类方法通过@classmethod装饰器实现,类方法与普通方法的区别是,类方法只能访问类变量,不能访问实例变量。因为添加classmethod后,self不代表实例,而代表类本身,所以类方法可以直接用类去调用,也可以用实例对象去调用。

静态方法:静态方法不能访问类变量,也不能访问实例变量, 在类中使用 @staticmethod 来修饰的方法属于静态方法,静态方法不需要指定任何的默认参数,静态方法可以通过类和实例去调用,静态方法,基本上是一个和当前类无关的方法,它只是一个保存到当前类中的函数,静态方法一般都是一些工具方法,和当前类无关

class fun():
    n = 1
    def __init__(self,age):
        self.age = age
        pass
    @classmethod            #类方法
    def fun1(cls,name):
        print('i am classmethod',name,cls.n)
    @staticmethod       #静态方法
    def fun2():    #此处不能带self,因为不能访问类      变量或实例变量
        print('i am staticmethod')
a = fun(23)
fun.fun1('123')
a.fun2()

 

私有方法,私有变量

类中私有方法,和私有属性,外部无法访问,只能在类的内部访问,在方法前面添加__即可让该方法变成私有方法。私有变量也是类似。

class School():
    def __init__(self,name):
        self.name = name
    def __city(self):
        self.__address = '北京'
        print(self.__address)
    def call(self):
        self.__city()

sch = School('清华')
sch.call()

 

只读属性

@property装饰器来创建只读属性,@property装饰器会将方法转换为相同名称的只读属性,可以与所定义的属性配合使用,这样可以防止属性被修改。

class Fight(object):
    def __init__(self,name):
        self.name = name
    def checking_status(self):
        print("connecting airline company api ...")
        print("checking fight %s status"%self.name)
        return 1 #1:到达 2:未到达
    @property
    def fight_status(self):     #get
        status = self.checking_status()
        if status == 0:
            print("fight got canceled...")
        if status == 1:
            print("fight is arriver")
        if status == 2:
            print("fight is not arriver")
    @fight_status.setter
    def fight_status(self,status):     #set
        print("changing...fight status",status)
        self.status = status
    @fight_status.deleter              #del
    def fight_status(self):
        print("del...")
f = Fight("A1292")
f.fight_status  #将fight_statu方法变为一种属性,不用加()即可调用
f.fight_status = 2  #正常情况下不能对该属性方法赋值,只能重新定义一个fight_status.setter的方法
del f.fight_status

 

 

 

posted @ 2022-11-13 23:32  powfu  阅读(35)  评论(0)    收藏  举报