Class 3 To Class 5 Python OOPs Concepts
Class 3 To Class 5 Python OOPs Concepts
Learning outcomes
To understand the basic concepts of OOPS
To demonstrate how the OOPS apply in
python
OOPS-INTRODUCTION
In Python, object-oriented Programming
(OOPs) is a programming paradigm that uses
objects and classes in programming.
Class
Objects
Polymorphism
Encapsulation
Inheritance
Data Abstraction
Python Class
#Statement-1 . . .
# Statement-N
Creating an Empty Class in Python
# Python3 program to
# demonstrate defining
# a class
class Dog:
pass
Python Objects
obj = Dog()
The Python self
class Dog:
# class attribute
attr1 = "mammal"
# Instance attribute
def __init__(self, name):
self.name = name
# Driver code
# Object instantiation
Rodger = Dog("Rodger")
Tommy = Dog("Tommy")
attr1 is a class attribute set to the value “mammal”. Class attributes are
shared by all instances of the class.
__init__ is a special method (constructor) that initializes an instance of the
Dog class. It takes two parameters: self (referring to the instance being
created) and name (representing the name of the dog). The name parameter
is used to assign a name attribute to each instance of Dog.
The speak method is defined within the Dog class. This method prints a
string that includes the name of the dog instance.
The driver code starts by creating two instances of the Dog class: Rodger and
Tommy. The __init__ method is called for each instance to initialize their
name attributes with the provided names. The speak method is called in both
instances (Rodger.speak() and Tommy.speak()), causing each dog to print a
statement with its name.
Creating Classes and objects with methods
class Dog:
# class attribute
attr1 = "mammal"
# Instance attribute
def __init__(self, name):
self.name = name
def speak(self):
print("My name is {}".format(self.name))
# Driver code
# Object instantiation
Rodger = Dog("Rodger")
Tommy = Dog("Tommy")
# Accessing class methods
Rodger.speak()
Tommy.speak()
Output
My name is Rodger
My name is Tommy
Python Inheritance
def display(self):
print(self.name)
print(self.idnumber)
def details(self):
print("My name is {}".format(self.name))
print("IdNumber: {}".format(self.idnumber))
# child class
class Employee(Person):
def __init__(self, name, idnumber, salary, post):
self.salary = salary
self.post = post
def details(self):
print("My name is {}".format(self.name))
print("IdNumber: {}".format(self.idnumber))
print("Post: {}".format(self.post))
# Python program to
# demonstrate private members
# Calling constructor of
# Base class
Base.__init__(self)
print("Calling private member of base class: ")
print(self.__c)
# Driver code
obj1 = Base()
print(obj1.a)