![](/img/trans.png)
[英]Python: How to use __add__ special method to add instances of the same class that return another instance of that class
[英]How to apply __add__ method to an infinite count of class instances?
例如,我有一個 class 並且通過在它的實例上使用__add__
方法,我想添加他們的薪水。
class Employee():
def __init__(self,salary):
self.salary = salary
def __add__(self,other):
return self.salary + other.salary
emp_1 = Employee(4000)
emp_2 = Employee(5000)
emp_3 = Employee(8000)
它不適用於 3 個或更多 arguments: print(emp_1 + emp_2 + emp_3)
輸出TypeError: unsupported operand type(s) for +: 'int' and 'Employee'
。 2個以上的實例怎么加起來?
如果你堅持繼續這個糟糕的、糟糕的、不好的想法,你可以做的是編寫你的__add__
方法,以便它知道如何將整數和Employee
實例添加到自身,並定義__radd__
以便當左邊的項目是 integer,您的 class 仍然有機會進行添加。
由於數字的加法是可交換的, __radd__
可以與__add__
相同。
class Employee():
def __init__(self, salary):
self.salary = salary
def __add__(self, other):
if isinstance(other, Employee):
other = other.salary
return self.salary + other
__radd__ = __add__
如果您想支持任何其他具有salary
屬性的 object,而不僅僅是您的Employee
class 的實例,您可以編寫__add__
如下:
def __add__(self, other):
# get other.salary if it exists, otherwise just use other
return self.salary + getattr(other, "salary", other)
這是可以做到的,但我想再次強調這是一個壞主意。 增加員工沒有意義。 當你在這里添加年齡或性別時會發生什么? 臨時 Employee 實例的性別是什么?
class Employee():
def __init__(self,salary):
self.salary = salary
def __add__(self,other):
return Employee(self.salary + other.salary)
def __repr__(self):
return f"${self.salary}"
emp_1 = Employee(4000)
emp_2 = Employee(5000)
emp_3 = Employee(8000)
print( emp_1 + emp_2 + emp_3 )
Output:
$17000
這是另一種方式,基於 sj95126 的評論。 在這里,添加返回一個 integer,我們添加一個添加覆蓋,可以將自身添加到一個簡單的 integer。 這不使用__repr__
方法。
class Employee():
def __init__(self,salary):
self.salary = salary
def __radd__(self,other):
return self.salary + other
def __add__(self,other):
return self.salary + other.salary
def __repr__(self):
return f"${self.salary}"
emp_1 = Employee(4000)
emp_2 = Employee(5000)
emp_3 = Employee(8000)
print( emp_1 + emp_2 + emp_3 )
Output:
17000
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.