37,719
社区成员
发帖
与我相关
我的任务
分享
class Test(object):
def __init__(self):
self.value = 0
t = Test()
t.dd = 32
print t.dd
print t.__dict__
>>>
32
{'dd': 32}
class Test(object):
def __init__(self):
self._value = {}
def __get__(self, instance, instance_type):
return self._value.get(instance, 0)
def __set__(self, instance, value):
self._value[instance] = value
t = Test()
t.dd = 32
print t.dd
print t.__dict__
>>>
32
{'_value': {}, 'dd': 32}
class Test(object):
def __init__(self):
self._value = {}
def __get__(self, instance, instance_type):
print "call __get__"
return self._value.get(instance, 0)
def __set__(self, instance, value):
self._value[instance] = value
class Another(object):
test = Test()
if __name__ == "__main__":
print Another().test
返回值:
call __get__
0
__get__基本是用来处理调用这个类的类的,
但是 这里有些问题也是要明确的。
如将上述代码改为:
class Test(object):
def __init__(self):
self._value = {}
def __get__(self, instance, instance_type):
print "call __get__"
return self._value.get(instance, 0)
def __set__(self, instance, value):
self._value[instance] = value
class Another(object):
def __init__(self):
self.test = Test()
if __name__ == "__main__":
print Another().test
输出变为:
<__main__.Test object at 0x024E64B0>
可以通过如下代码知道:
class Test(object):
def __init__(self):
self._value = {}
def __get__(self, instance, instance_type):
print "call __get__"
return self._value.get(instance, 0)
def __set__(self, instance, value):
self._value[instance] = value
class Another0(object):
def __init__(self):
self.test = Test()
class Another1(object):
test = Test()
if __name__ == "__main__":
print dir(Another0)
print dir(Another1)
print dir(Another0())
print dir(Another1())
上述对于类的初始化方法 不能在__init__中进行
个人比较讨厌python这种“初始化”不明确“导致的可能混淆”