示例
class A:
explanation = 'this is my problem'
def normal_method(self, name):
# print(self) # 实例方法隐含的参数为类实例self
print(self.explanation)
@classmethod
def class_method(cls, explanation):
# print(cls) # 类方法隐含的参数为类本身cls
print(cls.explanation)
@staticmethod
def static_method(explanation): # 静态方法无隐含参数
print(explanation)
a = A()
a.explanation = 'this is new'
print(a.normal_method('explanation')) # this is new
# print(A.normal_method('explanation')) # error 实例方法(普通方法)应该由实例调用,类不能调用
print(a.class_method('explanation')) # this is my problem
print(A.class_method('explanation')) # this is my problem
print(a.static_method('haha')) # haha
print(A.static_method('wawa')) # wawa
# b = A()
# print(b.normal_method('explanation')) # this is new
# print(b.class_method('explanation')) # this is my problem
总结
实例方法(普通方法)———>随着实例属性的改变而改变
类方法(无论是类调用还是实例调用)———>都是类属性的值,不随实例属性的变化而变化
静态方法———>不可以访问类属性,故直接输出传入方法的值