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)
  wallet = 0
  
  ## 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 .

p1 = Person('Yong')  
p2 = Person('Gan',200)
p3 = Kid('Jolin',50)    ## will call superclass constructor too
## 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.say_hi()    ## p1 is initialized with a base class
p1.balance()   ## this is a base class method
p1.MakeCry()   ## Error ! because it is trying to call an inherited class which does not exist
## 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.Cry()       ## p3 is initialized with an inherited class
p3.MakeCry()   ## Success ! this is the base class  method, calling inherited class method
## Kid is crying
## Parent making kid cry
## Kid is crying

8.4 Attributes

8.4.1 Setter

p1.wallet = 999
p2.wallet = 999
p3.wallet = 999

8.4.2 Getter

p1.wallet
p2.wallet
p3.wallet
## 999
## 999
## 999