7 Object Oriented Programming

7.1 Defining Class

  • Every function within a class must have at least one parameter - self
  • Use init as the constructor function. init is optional
class Person:
  wallet = 0  # 
  def __init__(self, myname,money=0):   # constructor
      self.name = myname
      self.wallet=money
      print('I\'m in Person Constructor: {}'.format(myname))
  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):
      self.Cry()
      
class Kid(Person):
  def __init__(self, myname, money=0):
      print('I\'m in Kid Constructor: {}'.format(myname))
      super().__init__(myname=myname, money=money)
  def Cry(self):
      print('Kid is crying')

7.2 Constructor

p1 = Person('Yong')  
#:> I'm in Person Constructor: Yong
p2 = Person('Gan',200)
#:> I'm in Person Constructor: Gan
p3 = Kid('Jolin',50)
#:> I'm in Kid Constructor: Jolin
#:> I'm in Person Constructor: Jolin

7.3 Calling Method

p1.say_hi()
#:> Hello, my name is :  Yong
p1.balance()
#:> Wallet Balance: 0
p3.Cry()
#:> Kid is crying
p3.MakeCry()
#:> Kid is crying
p2.say_hi()
#:> Hello, my name is :  Gan
p2.balance()
#:> Wallet Balance: 200

7.4 Getting Property

p1.wallet
#:> 0
p2.wallet
#:> 200

7.5 Setting Property

p1.wallet = 900
p1.wallet
#:> 900