Skip to content

Instantly share code, notes, and snippets.

@yoniLavi
Last active June 3, 2023 01:25
Show Gist options
  • Select an option

  • Save yoniLavi/b3a507ce93b640960898e7d4e4167ceb to your computer and use it in GitHub Desktop.

Select an option

Save yoniLavi/b3a507ce93b640960898e7d4e4167ceb to your computer and use it in GitHub Desktop.
# My playing around with dataclass addition, to see how I'd implement this example without a static method:
# https://stackoverflow.com/a/49269322/493553
from copy import copy
from dataclasses import dataclass
@dataclass
class Stats:
strength: int = 0
speed: int = 0
intellect: int = 0
tenacity: int = 0
def __iadd__(self, other):
for attr in self.__dict__:
setattr(self, attr, getattr(self, attr) + getattr(other, attr))
return self
def __add__(self, other):
if not other:
return self
obj = copy(self)
obj += other
return obj
__radd__ = __add__
a = Stats(1, 2, tenacity=3)
b = Stats(4, 5, 6, 7)
print(sum([a, b])) # prints: Stats(strength=5, speed=7, intellect=6, tenacity=10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment