静态方法和类方法
method (普通方法):
通过实例调用时,可以引用类内部的任何属性和方法
classmethod (类方法):
无需实例化, 可以调用类属性和类方法,无法取到普通的成员属性和方法
staticmethod (静态方法):
无论用类调用还是用实例调用,都无法取到类内部的属性和方法, 完全独立的一个方法
练习
类方法
class Test(object):
x = 123
y = 456
def __init__(self):
self.y = 456
def bar1(self):
print('Hello world')
@classmethod
def bar2(cls):
print('Bad world')
@classmethod
def foo2(cls):
print(cls.x)
print(cls.y)
#cls.bar1()
cls.bar2()
调用
Test.foo2()
123
456
Bad world
静态方法
class Test(object):
x = 123
y = 456
def __init__(self):
self.y = 789
def bar1(self):
print('Hello world')
@classmethod
def bar2(cls):
print('Bad world')
@staticmethod
def bar3():
print('=========')
@staticmethod
def foo3(obj):
print(obj.x)
print(obj.y)
obj.bar1()
obj.bar2()
obj.bar3()
调用
Test.foo3(a)
123
789
Hello world
Bad world
=========
静态方法不可以直接调用对象的属性和方法
class Test(object):
x = 123
y = 456
def __init__(self):
self.y = 789
def bar1(self):
print('Hello world')
@classmethod
def bar2(cls):
print('Bad world')
@staticmethod
def bar3():
print(x)
Test.bar3()
Traceback (most recent call last):
File "<ipython-input-34-54fdf6d02d89>", line 1, in <module>
Test.bar3()
File "C:/Users/hong/Desktop/untitled3.py", line 20, in bar3
print(x)
NameError: name 'x' is not defined
静以修身,俭以养德!