python课堂整理35----静态属性、类方法、静态方法

一、静态属性(绑定实例)

其实就是数据属性

通过装饰器 @property 将函数属性伪装成数据属性

class Room:
    def __init__(self, name, owner, length, width, high):
        self.name = name
        self.owner = owner
        self.length = length
        self.width = width
        self.high = high
    @property
    def cal_vol(self): #计算体积
        return "%s的%s体积为%s"%(self.owner,self.name,self.length * self.width * self.high)

v1 = Room("我的小窝", "刘文豪",100, 100, 100)
print(v1.name) #实例查看数据属性

print( v1.cal_vol) #静态属性查看体积

 

二、类方法 (绑定类)

将@calssmethod 写在类里面的函数前,该函数称为类方法

不需要实例化,类可以直接调用,但是只能访问类属性

class Lie_method:
    tag = 10
    def __init__(self, name, age):
        self.name = name
        self.age = age
    @classmethod
    def Lei_info(cls):  #默认的参数为 cls ,指的就是这个类名(Lie_method)
        print("类方法结果为%s"%(cls.tag))

    @classmethod
    def test(cls, x):
        print("无聊的下午%s%s"%(cls.tag, x))

Lie_method.Lei_info()
Lie_method.test("想")

三、静态方法  (即不绑定类,又不绑定函数)

通过 @staticmethod 绑定函数

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

class Room:
    def __init__(self, name, owner, length, width, high):
        self.name = name
        self.owner = owner
        self.length = length
        self.width = width
        self.high = high
    @property
    def cal_vol(self): #计算体积
        return "%s的%s体积为%s"%(self.owner,self.name,self.length * self.width * self.high)

    @staticmethod
    def take_bath(x, y):
        print("%s和%s正在洗澡"%(x, y))

Room.take_bath('小明','小红')  #通过类的点方法调用
v1 = Room("我的小窝", "刘文豪",100, 100, 100)
v1.take_bath('小明','小红')  #也可以通过实例调用

一个奋斗中的产品小白
原文地址:https://www.cnblogs.com/dabai123/p/11442700.html