請解釋@classmethod 和@staticmethod 的用法和區別
- 共同點
- 區別
- @staticmethod 不需要表示自身對象的self和自身類的cls參數,就像普通函數一樣定義
- @classmethod 也不需要self參數,但第二個參數需要是表示自身的cls參數,避免硬編碼
class MyClass:
bar = 1
def __init__(self):
self.count = 20
def process(self):
print('process', self.count)
@staticmethod
def static_process():
print('static_process')
print(MyClass.bar)
@classmethod
def class_process(cls):
print('class_process')
print(cls.bar)
print(cls)
cls().process()
print(cls().count)
print(MyClass.bar)
MyClass.static_process()
MyClass.class_process()
MyClass.bar = 123
MyClass.static_process()
1
static_process
1
class_process
1
<class '__main__.MyClass'>
process 20
20
static_process
123
54 - 元類(metaclass)的作用