第个形参是类对象的法
需要装饰 @classmethod 来标识其为类法,对于类法,第个参数必须是类对象,般
以 cls 作为第个参数。
class Dog(object):
__type = "狗"
# 类法,classmethod来进修饰
@classmethod
def get_type(cls):
return cls.__type
print(Dog.get_type())
使场景: - 当法中 需要使类对象 (如访问私有类属性等)时,定义类法 - 类法般和类属性配
合使
需要通过装饰 @staticmethod 来进修饰,静态法既需要传递类对象也需要传递实对象
(形参没有self/cls)。
静态法 也能够通过 实对象 和 类对象 去访问。
class Dog(object):
type = "狗"
def __init__(self):
name = None
# 静态法
@staticmethod
def introduce(): # 静态法会动传递实对象和类对象
print("科哺乳动物,属于..")
dog1 = Dog()
Dog.introduce() # 可以 实对象 来调 静态法
dog1.introduce() # 可以 类对象 来调 静态法
使场景: - 当法中 既需要使实对象(如实对象,实属性),也需要使类对象 (如类属
类法、静态法
1. 类法
2. 静态法
千锋Python人工智能学院
评论0