Python中的__get__和__set__特殊方法

实例:

>>> class A:
	def __get__(self, instance, cls):
		print(self, instance, cls, sep='\n')
		print(instance.name)
		return 2

>>> class B:
	a = A()
	def __init__(self):
		self.name = "BBB"

		
>>> b = B()
>>> b.a
<__main__.A object at 0x0000021CD5D78630>
<__main__.B object at 0x0000021CD5D78898>
<class '__main__.B'>
BBB
2


下面为测试其它情况示例:

>>> class B:
	def __init__(self):
		self.name = "BBB"
		self.a = A()

>>> b = B()
>>> b.a
<__main__.A object at 0x0000021CD5D78550>


 

 

 

展开阅读全文