Python_静态属性,类方法,静态方法

静态属性:把方法变成像属性一样调用

未使用静态属性的:

class House:
    owner = "James"
    def __init__(self,name,width,length,heigh):
        self.name = name
        self.width = width
        self.length = length
        self.heigh = heigh

    def cal_area(self):
        return (self.width * self.length)

toilet = House("厕所",90,90,200)
print(toilet.cal_area())
print(toilet.owner)

 

使用静态属性后:

class House:
    owner = "James"
    def __init__(self,name,width,length,heigh):
        self.name = name
        self.width = width
        self.length = length
        self.heigh = heigh

    #有点像装饰器?
    @property
    def cal_area(self):
        return (self.width * self.length)

toilet = House("厕所",90,90,200)
#不同就在于我不用执行方法了,cal_area就像是一个可以直接调用的属性,好处:隐藏了调用的方法逻辑
print(toilet.cal_area)
print(toilet.owner)

 

类方法:不用实例化就可以执行类的方法

class House:
    owner = "James"
    def __init__(self,name,width,length,heigh):
        self.name = name
        self.width = width
        self.length = length
        self.heigh = heigh

    #不用实例,就可用类本身去调用的方法,就叫类方法
    @classmethod
    def cal_area(self,info):
        return ("%s" %info)

print(House.cal_area("随便写点什么嗯嗯"))

 

静态方法:名义上的归属类管理,类的工具包, 不能使用类变量和实例变量

class House:
    owner = "James"
    def __init__(self,name,width,length,heigh):
        self.name = name
        self.width = width
        self.length = length
        self.heigh = heigh

    @staticmethod
    def wash_house(a,b,c):
        print(a+b+c)

#就像是一个普通的方法调用,没有默认的实例变量或者是类方法中的类变量
House.wash_house(1,2,3)
#
yangtai = House("阳台",8,10,20)
#实例会多出一个yangtai本身的参数,会报错(没报,可能是python版本问题)
yangtai.wash_house(1,2,3)

 

posted on 2019-08-12 23:29  詹生  阅读(4862)  评论(0编辑  收藏  举报

导航