class
Inheritance
allows a class to inherit attributes and methods from another class(superclass)
Overriding method: subclass can override methods inherited from the superclass
#overriding method
class Poodle(Dog):
def bark(self):
return "yelp"
pod1 = Poodle("c",2)
print(pod1.bark())
calling superclass methods with “super()” keyword
class GermanShepherd(Dog):
def __init__(self,name,age):
self.kk = 'asdf'
def bark(self):
self.kk = "asdf"
super().bark()
Encapsulation
concept of hiding the internal implementation details of a class from the outside world. achieved by private and protected access modifiers
# encapsulation -> hide functionality if a ckass from the outside world
class Person:
def __init__(self,name,age):
self._namename = name
self.__age = age
def get_age(self):
return self.__age
def set_age(self,age):
self.__age = age
jay = Person("jay",3)
#accessing private variable, attributes
print(jay._Person__age)
# accessing via public method
print(jay.get_age())
Polymorphism
#polyorphism
# allow bojcet of diff classes to be treated as object of a common super class,it enables the same method name to behave differently for different classes
class Bird:
def fly(self):
return "bird flying high"
class Fish:
def swim(self):
return "fish swim"
def move(animal):
if isinstance(animal, Bird):
return animal.fly()
elif isinstance(animel, Fish):
return animal.swim()
bird = Bird()
fish = Fish()
print(move(bird))
Abstract base class(abc)
# @abstract base classes
# allows you to define abstract methods that must be implemented by subclasses.
# they provide a way to define common interfaces for related classes
from abc import ABC, abstractmethod
class Shape(ABC):
@abstractmethod
def area(self):
pass
class Square(Shape):
def __init__(self,side):
self.side = side
def area(self):
return self.side**2
square = Square(5)
print(square.area())