Chapter 8 Object Oriented Programming
8.1 Defining Class
- Every function within a class must have at least one parameter - self
- Use init as the constructor function (optional)
## Base Class
class Person:
## this section defines the attributes (setter and getter possivle)
= 0
wallet
## Constructor (Optional)
def __init__(self, myname, money=0):
self.name = myname
self.wallet=money
print('I\'m in Person Constructor: {}'.format(myname))
## Here are the Methods (notice first parameter 'self' is mandatory)
def say_hi(self):
print('Hello, my name is : ', self.name)
def say_bye(self):
print('Goodbye', Person.ID)
def take(self,amount):
self.wallet+=amount
def balance(self):
print('Wallet Balance:',self.wallet)
def MakeCry(self):
print('Parent making kid cry')
self.Cry()
## Inherit From Base class
class Kid(Person):
def __init__(self, myname, money=0):
print('I\'m in Kid Constructor: {}'.format(myname))
super().__init__(myname=myname, money=money) ## call the base constructor
def Cry(self):
print('Kid is crying')
8.2 Constructor
Calling a constructor will NOT automatically call it’s superclass contrustor. Example above use super()
from child class to call base class constructor .
= Person('Yong')
p1 = Person('Gan',200)
p2 = Kid('Jolin',50) ## will call superclass constructor too p3
## I'm in Person Constructor: Yong
## I'm in Person Constructor: Gan
## I'm in Kid Constructor: Jolin
## I'm in Person Constructor: Jolin
8.3 Methods
A base class method can call its inherited class method (if available, otherwise Error)
## p1 is initialized with a base class
p1.say_hi() ## this is a base class method
p1.balance() ## Error ! because it is trying to call an inherited class which does not exist p1.MakeCry()
## Hello, my name is : Yong
## Wallet Balance: 0
## Error in py_call_impl(callable, dots$args, dots$keywords): AttributeError: 'Person' object has no attribute 'Cry'
## p3 is initialized with an inherited class
p3.Cry() ## Success ! this is the base class method, calling inherited class method p3.MakeCry()
## Kid is crying
## Parent making kid cry
## Kid is crying