Your cart is currently empty!
Basic Python OOP
This note is taken from InteractivePython.org website.
Create Class in Python
class Perth: def __init__(self, age, city): # __init__ is reserved word for initializing the class. self is required as argument. self.age = age self.city = city thisperth = Perth(25, 'Melbourne')
Write any function
def func_name(arg):
or overwrite functions (Operator Overloading)
e.g. overwrite print(thisperth)
class Perth: # .... def __str__(self): return self.age
- use __str__ to overwrite print(a)
- use __add__ to overwrite a + b
- use __eq__ to overwrite a == b
- Other methods can be found here: Python 3 References, Python 3 Magic Methods
Inheritance: Creating Subclass
Inheritance can be done by using parent class (or Superclass) name like so.
class Perthchild(Perth):
Subclass will get everything from Superclass, and has to call Superclass’s __init__ in its init e.g.
def __init__(self, age, city): Perth.__init__(self, age, city)
Beware that in order to create subclass, subclass and superclass should have IS-A Relationship, not HAS-A Relationship (e.g. cat IS animal, and cat house HAS cats)
by
Tags:
Leave a Reply