Skip to content

Instantly share code, notes, and snippets.

@ishankhare07
Last active August 22, 2016 21:41
Show Gist options
  • Save ishankhare07/e7e56ee80da3a424a2baed67995497a8 to your computer and use it in GitHub Desktop.
Save ishankhare07/e7e56ee80da3a424a2baed67995497a8 to your computer and use it in GitHub Desktop.
Anatomy of python classes | run this code here -> https://repl.it/CqLt/3
def add(self, other): # overloading + operator
return self.__class__(self.a + other.a, self.b + other.b)
def sub(self, other): # overloading - operator
return self.__class__(self.a - other.a, self.b - other.b)
def constructor(self, a = 0, b = 0): # to be constructor
self.a = a
self.b = b
def repr(self): # overload output stream
return '<{0}: {1}+i{2} >'.format(self.__class__.__name__, self.a, self.b)
c = type('Complex', (object,), { # monkeypatch B-)
'__add__': add,
'__sub__': sub,
'__init__': constructor,
'__repr__': repr
})
c1 = c(1, 2)
c2 = c(1, 1)
print(c1, c2)
print(c1+c2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment