一、类属性
1.1 定义
类属性就是 类对象 所拥有的属性,它被 该类的所有实例对象 所共有,可以使用 类对象 或 实例对象 访问。
1.2 优点
类属性背被全类所共有,仅占⽤一份内存,更加节省内存空间。
1.3 设置、访问与修改操作
访问可以通过 类调用 或者 实例对象调用。
class Washer(object):
#设置类属性
brand = '海尔'
#调用类属性
#类调用
print(Washer.brand)
#实例对象调用
wash = Washer()
print(wash.brand)
# 修改类属性
Washer.brand='美的'
print(Washer.brand)#美的
print(wash.brand)#美的
# 不能通过对象修改属性,如果这样操作,则是创建了一个实例属性
wash.brand = '松下'
print(Washer.brand)#美的
print(wash.brand)#松下
二、类方法
2.1 定义
需要用装饰器 @classmethod 来标识其为类⽅法,对于类⽅法,第⼀个参数必须是类对象,一般以cls 作为第⼀个参数。主要是用来调用私有类属性。
2.2 使用
class Washer(object):
#设置私有类属性
__brand = '海尔'
@classmethod
def get_brand(cls):
return cls.__brand
wash = Washer()
print(wash.get_brand())#海尔
三、静态方法
3.1 定义
需要通过装饰器@staticmethod
来进行修饰,静态方法既不需要传递类对象也不需要传递实例对象(形参没有self/cls)。可以通过 实例对象 和 类对象 去访问。
3.2 优点
不需要参数传递,有利于减少不必要的内存占用和性能消耗。
3.3 使用
class Washer(object):
#定义静态类方法
@staticmethod
def printf():
print('这是一类洗衣机')
#类直接调用
Washer.printf()
#实例对象调用
wash = Washer()
wash.printf()
静态方法既可以使用 对象 访问 又可以使用 类 访问。