我想要实现的是这样的:
class object:
def __init__(self):
WidthVariable(self)
print self.width
#Imagine I did this 60frames/1second later
print self.width
#output:
>>0
>>25
我想要发生的事情(如上):WidthVariable创建一个类时,它会将变量添加width到对象实例中。这个变量就像一个普通的属性,但在这种特殊情况下它是只读的(只fget设置了变量)。此外,fget调用定义在WidthVariable其中决定width返回什么的函数。
但是,我不知道该怎么做!我使用普通属性进行了尝试,但我发现它们只适用于类而不是每个实例 - 请注意我使用的代码应该与上面的代码尽可能相似(即只有__init__of 中的代码WidthVariable应该设置width变量,其他任何地方都没有) . 另外,self.width不能是功能,因为我不喜欢它self.width(),我想要self.width(因为它与我拥有的其余设计保持一致)。
为了澄清,完整的代码将是这样的:
class MyObject:
def __init__(self)
WidthVariable(self)
print self.width
class WidthVariable:
def __init__(self, object)
object.width = property(self.get_width)
def get_width(self):
value = #do_stuff
return value #The Value
#output:
>>25 #Whatever the Value was