【发布时间】:2014-04-19 17:31:27
【问题描述】:
我希望推出自己的简单对象,该对象可以跟踪变量的单位(也许我也会添加其他属性,例如公差)。这是我目前所拥有的:
class newVar():
def __init__(self,value=0.0,units='unknown'):
self.value=value
self.units=units
def __str__(self):
return str(self.value) + '(' + self.units + ')'
def __magicmethodIdontknow__(self):
return self.value
diameter=newVar(10.0,'m') #define diameter's value and units
print diameter #printing will print value followed by units
#intention is that I can still do ALL operations of the object
#and they will be performed on the self.value inside the object.
B=diameter*2
因为我没有正确的魔术方法,所以我得到以下输出
10.0(m)
Traceback (most recent call last):
File "C:\Users\user\workspace\pineCar\src\sandBox.py", line 25, in <module>
B=diameter*2
TypeError: unsupported operand type(s) for *: 'instance' and 'int'
我想我可以重写每个魔术方法来只返回 self.value 但这听起来是错误的。也许我需要一个装饰器?
另外,我知道我可以调用 diameter.value 但这似乎是重复的
【问题讨论】:
-
您想通过对您的值进行操作来保留(和更新)您的单位吗?例如,
newVar(10, "m") / newVar(5, "s")是否应该给另一个newVar实例,其单位为m / s? -
你可能想在这里使用a library
标签: python magic-methods