Skip to content

Instantly share code, notes, and snippets.

@grihabor
Last active November 1, 2017 07:40
Show Gist options
  • Save grihabor/6592c49a4d1f6442985f35ef42fb097f to your computer and use it in GitHub Desktop.
Save grihabor/6592c49a4d1f6442985f35ef42fb097f to your computer and use it in GitHub Desktop.
Implement operator + for a custom class #example
class Color:
def __init__(self, r, g, b):
self.r = r
self.g = g
self.b = b
def __add__(self, other):
return Color(
(self.r + other.r) // 2,
(self.g + other.g) // 2,
(self.b + other.b) // 2,
)
white = Color(255, 255, 255)
black = Color(0, 0, 0)
gray = white + black
print(gray.r, gray.g, gray.b)
#|127 127 127
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment