Python (Level-5): Class advanced( Inheritance, Polymorphism, Encapsulation, Access modifier, Class method, and Static method )

Access Modifiers

Object-oriented languages, like C++ and Java, use various keywords to control and restrict the resource usage of a class. This is where keywords like publicprivateand protected come into the picture. However, Python has a different way of providing the functionality of these access modifiers.

class Modifiers:

    def __init__(self, name):
        self.__private_member = name  # Private Attribute

m = Modifiers("SKAUL05")
print(m.__private_member)

Followings are the main Concepts of Object-Oriented Programming (OOPs) 

- Class

- Objects

- Inheritance

- Polymorphism

- Encapsulation






Inheritance
Inheritance allows us to define a class(child class/ sub class) that inherits all the methods and properties from another class(parent class/ super class).


class Person:
  def __init__(self, first_name, last_name):
    self.first_name = first_name

    self.last_name = last_name

  def print_name(self):
    print(self.first_name, self.last_name)

class Student(Person):
  def __init__(self, first_name, last_name, entrance_year):
    super().__init__(first_name, last_name)
    self.entrance_year = entrance_year

  def welcome(self):
    print("Welcome", self.first_name, self.last_name);
    print(f"You are in {self.entrance_year}.")


Polymorphism

Polymorphism lets us define methods in the child class that have the same name as the methods in the parent class.


def get_bird_info(obj): 
    obj.intro()
    obj.flight() 

get_bird_info(bird1)
get_bird_info(sparrow1)
get_bird_info(chicken1)




Encapsulation

- Encapsulation is one of the fundamental concepts in object-oriented programming (OOP). 
- This puts restrictions on accessing variables and methods directly and can prevent the accidental modification of data.
- To prevent accidental change, an object’s variable can only be changed by an object’s method. Those types of variables are known as private variables.


class Base:

    def __init__(self):
        self.a = "public variable"
        self.__b = "private variable"
  

class Derived(Base):

    def __init__(self):
        Base.__init__(self)
        print(self.__b)

Class method and Static method(under construction...)


Let's study above topic using example code. 


Comments

Popular posts from this blog

Python (Level-1): Introductions

Python (Level-3): Data Types

Processing Language(Level-1): Game Coding.