我有一個具有以下結構的類:
class Example:
def __init__(self, value, foo):
self.value = value
self.foo = foo
self.bar = self.modify_stuff(value, foo)
def modify_stuff(self, value, foo):
""" some code """
pass
我想創建一個類的實體,然后可以value直接參考,像這樣:
ex = Example(3, 'foo')
ans = 5 ex
代替:
ans = 5 ex.value
我怎樣才能做到這一點?
uj5u.com熱心網友回復:
重寫add和radd:
class Example:
def __init__(self, value):
self.value = value
def __add__(self, other):
if isinstance(other, Example):
return self.value other.value
return self.value other
def __radd__(self, other):
if isinstance(other, Example):
return self.value other.value
return self.value other
print(Example(3) 5)
print(Example(4) Example(2))
# 8
# 6
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/498102.html
