作爲替代mgilson's excellent answer,你可以繼承int
到自定義類來實現這個
>>> class V(int):
... def __new__(cls,val,**kwargs):
... return super(V,cls).__new__(cls,max(val,0))
然後直接使用它:
>>> A=V(200)
200
>>> B=V(-140)
0
>>> [V(i) for i in [200, -140, 400, -260]]
[200, 0, 400, 0]
>>> A,B,C,D = [V(i) for i in [200, -140, 400, -260]]
唯一的優勢做這個方式是,然後你可以覆蓋__sub__
和__add__
__mul__
適當,然後你V ints將總是大於0,即使你有a=V(50)-100
例子:
>>> class V(int):
... def __new__(cls,val,**kwargs):
... return super(V,cls).__new__(cls,max(val,0))
... def __sub__(self,other):
... if int.__sub__(self,other)<0:
... return 0
... else:
... return int.__sub__(self,other)
>>> a=V(50)
>>> b=V(100)
>>> a-b #ordinarily 50-100 would be -50, no?
0
值得一提的是''CapWords''在Python通常保留給類 - 檢查[Python的風格指南(PEP-8 )](http://www.python.org/dev/peps/pep-0008/)獲取更多信息。 –
我很確定python社區會建議像'A,B,C,D'這樣的晦澀的變量名:^)。 – mgilson