Python 中 @classmethod 的理解

@classmethod:

1.实列与类均可调用;

2.类自动赋值方法第一个参数(cls)


>>> class T(type):
	def __new__(cls, name, base, attrs):
		new_cls = type.__new__(cls, name, base, attrs)
		instance.append(new_cls)
		print(len(instance))
		cls.get_instance()
		return new_cls
	@classmethod
	def get_instance(cls):
		print('cls')

		
>>> class TT(metaclass=T):
	pass

5
cls
>>> 


 >>> class T:
	def __init__(self):
		self.t()
	@classmethod
	def t(cls):
		print(cls)

		
>>> T.t()
<class '__main__.T'>
>>> t = T()
<class '__main__.T'>
>>> t.t()
<class '__main__.T'>
>>> 



 

 

展开阅读全文