任何一种类型的方法,都可以用类或者对象来调用
那什么时候使用对象方法,什么时候使用类方法和静态方法?
- 在绝大部分情况下,我们的方法都会声明成 对象方法
- 如果我们希望用类来处理这个方法,或者不希望某一个属性值不因为对象 而改变的时候,就可以用类方法
- 静态方法的使用绝大部分都可以用实例方法或者类方法来替代
class People(object):
# 类属性
count = 0
size = 0
def __init__(self, name='', age=''):
# 对象属性
self.name = name
self.age = age
# 对象方法
def say(self):
print('hai')
# 类方法
@classmethod
def classFun(cls):
print('Hello,我是类方法')
# 静态方法
@staticmethod
# 不需要指定self或者cls来调用
def method():
print('我是静态方法')
People.classFun() # Hello,我是类方法
People.method() # 我是静态方法
p1 = People()
p1.classFun() # Hello,我是类方法
p1.method() # 我是静态方法
p1.say() # hai
People.say(p1) # hai
People.say(People()) # hai