我想要滚动我自己的简单对象,可以跟踪变量的单位(也许我会添加其他属性,如公差).这是我到目前为止:
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
Run Code Online (Sandbox Code Playgroud)
因为我没有正确的魔术方法,所以我得到以下输出
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 *: …Run Code Online (Sandbox Code Playgroud)