You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
#Creat Class ExampleclassMyClass:
x=05#Member of MyClassy=10#Member of MyClassmy_class_object=MyClass()
print(my_class_object) #See what happens when you print objectprint(my_class_object.x) #This should print x value which is member of MyClass
classParrot:
# class attributespecies="bird"# instance attributedef__init__(self, name, age):
self.name=nameself.age=age# instantiate the Parrot classblu=Parrot("Blu", 10)
woo=Parrot("Woo", 15)
# access the class attributesprint("Blu is a {}".format(blu.__class__.species))
print("Woo is also a {}".format(woo.__class__.species))
# access the instance attributesprint("{} is {} years old".format( blu.name, blu.age))
print("{} is {} years old".format( woo.name, woo.age))
12.5 Encapsulation
# 1. Using OOP in Python, we can restrict access to methods and variables.# 2. This prevent data from direct modification which is called encapsulation.# 3. In Python, we denote private attribute using underscore as prefix i.e single "_" or double "__".classComputer:
def__init__(self):
self.__maxprice=900defsell(self):
print("Selling Price: {}".format(self.__maxprice))
defsetMaxPrice(self, price):
self.__maxprice=pricec=Computer()
c.sell()
# change the pricec.__maxprice=1000c.sell()
# using setter functionc.setMaxPrice(1500)
c.sell()
12.6 Methods
classParrot:
# instance attributesdef__init__(self, name, age):
self.name=nameself.age=age# instance methoddefsing(self, song):
return"{} sings {}".format(self.name, song)
defdance(self):
return"{} is now dancing".format(self.name)
# instantiate the objectblu=Parrot("Blu", 10)
# call our instance methodsprint(blu.sing("'Happy'"))
print(blu.dance())
classParrot:
deffly(self):
print("Parrot can fly")
defswim(self):
print("Parrot can't swim")
classPenguin:
deffly(self):
print("Penguin can't fly")
defswim(self):
print("Penguin can swim")
# common interfacedefflying_test(bird):
bird.fly()
#instantiate objectsblu=Parrot()
peggy=Penguin()
# passing the objectflying_test(blu)
flying_test(peggy)
'In the above program, we defined two classes Parrot and Penguin. Each of them have common method fly() method. However, their functions are different. To allow polymorphism, we created common interface i.e flying_test() function that can take any object. Then, we passed the objects blu and peggy in the flying_test() function, it ran effectively.'