类方法是以类对象作为第一个参数的方法。需要使用装饰器@classmethod
来标识其为类方法。对于类方法,第一个参数必须是类对象,一般以cls
作为第一个参数。
class Dog(object):
__type = "狗"
@classmethod
def get_type(cls):
return cls.__type
使用场景:
静态方法通过装饰器@staticmethod
来修饰,静态方法既不需要传递类对象也不需要传递实例对象(形参没有self/cls
)。静态方法也可以通过实例对象和类对象去访问。
class Dog(object):
type = "狗"
def __init__(self):
name = None
@staticmethod
def introduce():
print("犬科哺乳动物,属于食肉目..")
注意点:
class Dog:
def demo_method(self):
print("对象方法")
@classmethod
def demo_method(cls):
print("类方法")
@staticmethod
def demo_method():
print("静态方法")
dog1 = Dog()
Dog.demo_method() # 结果:静态方法
dog1.demo_method() # 结果:静态方法