DEV Community

Aruna Arun
Aruna Arun

Posted on

Day 10: Python Programming

Object Oriented Programming

1.What is OOP?
OOP helps you organize code using objects and classes.
OOP Features:

Class & Object
Constructors
Methods
Inheritance
Encapsulation
Polymorphism

Class and Object
Class Syntax
class Student:
pass
Object Syntax
s1 = Student()

Attributes & Methods
class Car:
def start(self): # method
print("Car started")

c = Car()
c.start()

Constructor
(init)
Automatically runs when object is created.
class Person:
def init(self, name, age):
self.name = name
self.age = age

p = Person("Aruna", 21)
print(p.name, p.age)

Types of Methods
1.Instance Method
def show(self):
print(self.name)

2.Class Method
Used for class-level data.
class Student:
school = "ABC School"

@classmethod
def show_school(cls):
    print(cls.school)
Enter fullscreen mode Exit fullscreen mode

3.Static Method
General utility methods.
@staticmethod
def add(a, b):
return a + b

Inheritance
Allows one class to use features of another.
1.Single Inheritance
class Parent:
def show(self):
print("Parent")

class Child(Parent):
pass

c = Child()
c.show()

2.Multilevel
class A:
pass

class B(A):
pass

class C(B):
pass

3.Multiple
class A:
pass

class B:
pass

class C(A, B):
pass

Polymorphism
Same function name, different behavior.
Method Overriding
class Animal:
def sound(self):
print("Some sound")

class Dog(Animal):
def sound(self):
print("Bark")

d = Dog()
d.sound()

Encapsulation
Protect data using private variables.
class Bank:
def init(self):
self.__balance = 0 # private

def deposit(self, amount):
    self.__balance += amount

def show(self):
    print(self.__balance)
Enter fullscreen mode Exit fullscreen mode

Top comments (0)