说我有我经常想要添加的属性(我通过添加实例来实现)。当我只有一些我想要添加的属性集时,我使用了__add__
方法。
但是现在,如果我有多个,我只是制作类方法,而不是使用这个特殊的dunder方法(__add__
)?
class Athlete():
def __init__(self, name, num_throws, num_games, minutes_played):
self.name = name
self.num_throws = num_throws
self.num_games = num_games
self.minutes_played = minutes_played
# I was using below method to calculate the total number of throws for 2 athletes
def __add__(self, other):
return self.num_throws * other.num_throws
# But now I have another addition to calculate the total number of minutes played
def __add__(self, other):
return self.minutes_played * other.minutes_played
ath1 = Athlete('John', 34, 19, 478)
ath2 = Athlete('Jim', 32, 11, 260)
print(ath1 + ath2)
因此,在上述情况下,是否需要使用__add__
?我应该制作自己添加内容的方法吗?
答案 0 :(得分:0)
您可以循环浏览属性并逐个添加。