Object oriented programming with python – Using classes (basic)

#!usr/bin/python3.3

#Inheritance
class Animal:
def walk(self): print(“Hey I am walking”)

#Defining a class
class Duck(Animal): #The Duck class inherits from the Animal class

#Constructor Method. Will be called when Object is created for this call
#Each Object would have a different value. This is called Encapsulation in OO prog.
def __init__(self,value):
print(“Constructor”)
self._v = value #should always use _v locally. If want to change outside the class use Setter/Getter methods
def quack(self): #self is a reference to the object
print(‘quaaccck’,self._v)

def wach(self):
print(‘waasd’,self._v)

def walk(self):
super().walk() #The super method is used when there is a same method in the parent class and you want to execute both the methods
print(“Hey This is the duck class executing”)

def main():

donald = Duck(22) #crearing an object of the class Duck
donald.quack()
donald.wach() #Here becasue of self donald is being passed donald.quack(donald)
donald.walk(); #The walk method in duck would take precedence over the walk method in Animal

if __name__ == “__main__”: main()

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s