【发布时间】:2009-06-19 16:54:44
【问题描述】:
我正在尝试学习描述符,但我对对象的行为感到困惑 - 在下面的两个示例中,据我了解 __init__ 它们应该工作相同。谁能解开我的疑惑,或者给我指出一个可以解释这一点的资源?
import math
class poweroftwo(object):
"""any time this is set with an int, turns it's value to a tuple of the int
and the int^2"""
def __init__(self, value=None, name="var"):
self.val = (value, math.pow(value, 2))
self.name = name
def __set__(self, obj, val):
print "SET"
self.val = (val, math.pow(val, 2))
def __get__(self, obj, objecttype):
print "GET"
return self.val
class powoftwotest(object):
def __init__(self, value):
self.x = poweroftwo(value)
class powoftwotest_two(object):
x = poweroftwo(10)
>>> a = powoftwotest_two()
>>> b = powoftwotest(10)
>>> a.x == b.x
>>> GET
>>> False #Why not true? shouldn't both a.x and b.x be instances of poweroftwo with the same values?
【问题讨论】:
-
您可能希望在输出中包含 type(a.x) 和 type(b.x)。
标签: python descriptor