Unit - 4 Classes and Object-Oriented Programming
Unit - 4 Classes and Object-Oriented Programming
Classes and
Object-oriented
Programming
In Python, object-oriented Programming (OOPs) is a
programming paradigm that uses objects and classes
in programming.
class Dog:
# class attribute
attr1 = "mammal"
# Instance attribute
def __init__(self, name):
self.name = name
Rodger = Dog("Rodger")
Tommy = Dog("Tommy")
# Accessing class attributes
print("Rodger is a {}".format(Rodger.__class__.attr1))
print("Tommy is also a {}".format(Tommy.__class__.attr1))
# Accessing instance attributes
print("My name is {}".format(Rodger.name))
print("My name is {}".format(Tommy.name))
Output
Rodger is a mammal
Tommy is also a mammal
My name is Rodger
My name is Tommy
Example 2: Creating Class 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))
# Object instantiation
Rodger = Dog("Rodger")
Tommy = Dog("Tommy")
# Accessing class methods
Rodger.speak() Output
Tommy.speak() My name is Rodger
My name is Tommy
# define a class
class Bike:
name = ""
gear = 0
# create object of class
bike1 = Bike()
# access attributes and assign new values
bike1.gear = 11
bike1.name = "Mountain Bike"
print(f"Name: {bike1.name}, Gears: {bike1.gear} ")
# define a class
class Employee:
employee_id = 0
employee1 = Employee()
employee2 = Employee()
employee1.employeeID = 1001
print(f"Employee ID: {employee1.employeeID}")
employee2.employeeID = 1002
print(f"Employee ID: {employee2.employeeID}")
An Instance Variable in Python
class Student:
# constructor
def __init__(self, name, age):
# Instance variable
self.name = name
self.age = age
# instance method access instance variable
def show(self):
print('Name:', self.name, 'Age:', self.age)
# create first object
print('First Student')
emma = Student("Jessa", 14)
# call instance method
emma.show()
class Student:
# Class variable
school_name = 'ABC School ‘
# constructor
def __init__(self, name):
self.name = name
# access class variable inside constructor using self
print(self.school_name)
# access using class name
print(Student.school_name)
# create Object
s1 = Student('Emma')
Example : Access Class Variable in Instance method and
outside class
class Student:
# Class variable
school_name = 'ABC School ‘
# constructor
def __init__(self, name, roll_no):
self.name = name
self.roll_no = roll_no
# Instance method
def show(self):
print('Inside instance method')
# access using self
print(self.name, self.roll_no, self.school_name)
# access using class name
print(Student.school_name)
# create Object
s1 = Student('Emma', 10)
s1.show()
print('Outside class')
# access class variable outside class O/P
# access using object reference Inside instance method
print(s1.school_name) Emma 10 ABC School
ABC School
# access using class name Outside class
print(Student.school_name) ABC School
ABC School
Class Method
Used to access or modify the class state. In method
implementation, if we use only class variables, then
such type of methods we should declare as a class
method. The class method has a cls parameter which
refers to the class.
A class method is bound to the class and not the
object of the class. It can access only class variables.
Class method works with the class since its parameter
is always the class itself.
The class method can be called both by the class and its
object.
Class.classmethod()
Or even
Class().classmethod()
But no matter what, the class method is always attached
to a class with the first argument as the class itself cls.
def classMethod(cls, args...)
Example : Create class method using classmethod()
class Person:
age = 25
def printAge(cls):
print('The age is:', cls.age)
# create printAge class method
Person.printAge = classmethod(Person.printAge)
Person.printAge()
O/P:
The age is: 25
Here, we have a class Person, with a member
variable age assigned to 25.
We also have a function printAge that takes a single
parameter cls and not self we usually take.
cls accepts the class Person as a parameter rather
than Person's object/instance.
Now, we pass the method Person.printAge as an
argument to the function classmethod. This converts
the method to a class method so that it accepts the
first parameter as a class (i.e. Person).
In the final line, we call printAge without creating a
Person object like we do for static methods. This prints
the class variable age.
Example : ( simple class method)
class bscit:
course = 'DSA'
def purchase(obj):
print("Purchase course : ", obj.course)
bscit.purchase = classmethod(bscit.purchase)
bscit.purchase()
Output:
Purchase course : DSA
Create class method using classmethod() :
class Student:
# create a variable
name = “Pythonfor python"
# create a function
def print_name(obj):
print("The name is : ", obj.name)
# create print_name classmethod
# before creating this line print_name()
# It can be called only with object not with class
Student.print_name = classmethod(Student.print_name)
# now this method can be called as classmethod
# print_name() method is called a class method
Student.print_name()
Static Methods in Python
A static method is a general utility method that
performs a task in isolation. Static methods in Python
are similar to those found in Java or C++.
A static method is bound to the class and not the object
of the class. Therefore, we can call it using the class
name.
A static method doesn’t have access to the class and
instance variables because it does not receive an implicit
first argument like self and cls. Therefore it cannot
modify the state of the object or class.
The class method can be called
using ClassName.method_name() as well as by using an
object of the class.
Example :
class Employee:
@staticmethod
def sample(x):
print('Inside static method', x)
# call static method
Employee.sample(10)
# can be called using object
emp = Employee() emp.sample(10)
Example :
class Calculator:
def addNumbers(x, y):
return x + y
# create addNumbers static method
Calculator.addNumbers = staticmethod(Calculator.addNumbers)
print('Product:', Calculator.addNumbers(15, 110))
Product: 125
Private Variables and Methods :
Private members in programming languages (such as
C++ and Java) are the members that are only available
to their own class. Neither the subclasses nor the
classes in the same package have access to them.
In Python, there is no such strict enforcement of
privacy. It does not have access specifiers like other
languages to make variables or methods private to the
class.
However, we can use the name mangling feature of
Python to make a variable or method appear as
restricted.
We have to prefix the __ (double underscore) in the name of
the variable to represent it as a private variable.
class BankAccount:
def __init__(self, balance):
self.__balance = balance
#private variable
def displayBalance(self):
print("Balance: ", self.__balance)
myaccount = BankAccount('85,33,999')
myaccount.displayBalance()
print(myaccount.__balance)
#outputs 'Balance: 85,33,999'
#AttributeError: object has no attribute '__balance‘
Accessing the variable __balance through object throws an error because Python has
scrambled its name to _BankAccount__balance (class name with leading underscore
followed by the name of the variable).
Python does it so to ensure that subclasses don’t
accidentally override the private attributes of the
parent class.
If we replace the name with _BankAccount__balance in
the print statement, then it works fine.
print(myaccount._BankAccount__balance)
#outputs '85,33,999‘
myaccount = BankAccount('85,33,999')
myaccount.__displayBalance()
# define a superclass
class super_class:
# attributes and method definition
# inheritance class
sub_class(super_class):
# attributes and method of super_class
# attributes and method of sub_class
# inherit from Animal
class Dog(Animal):
Example : # new method in subclass
class Animal: def display(self):
# access name attribute of
# attribute and method superclass using self
of the parent class print("My name is ", self.name)
name = ""
# create an object of the subclass
labrador = Dog()
def eat(self):
print("I can eat") # access superclass attribute and
method
labrador.name = "Rohu"
labrador.eat()
Output
I can eat # call subclass method
My name is Rohu labrador.display()
Example :
class Polygon:
# Initializing the number of sides
def __init__(self, no_of_sides):
self.n = no_of_sides
self.sides = [0 for i in range(no_of_sides)]
def inputSides(self):
self.sides = [float(input("Enter side "+str(i+1)+" : ")) for i
in range(self.n)]
def findArea(self):
a, b, c = self.sides
Enter side 1 : 3
Enter side 2 : 5
Enter side 3 : 4
Side 1 is 3.0
Side 2 is 5.0
Side 3 is 4.0
The area of the triangle is 6.00
Namespaces in Python
Output:
x and y refer to the same object
Variables in Python
Variables in Python are just references to the actual object
in memory. They are like names or labels that point to the
actual object in memory. They do not store any value.
Consider the following example:
a = 100
As discussed earlier, when the above code is executed, CPython
internally creates an object of type integer. The
variable a points to this integer object as shown below:
We can access the integer object in the Python program using
the variable a.
Let's assign this integer object to another variable b:
b=a
When the above code is executed, the variables a and b both
point to the same integer object, as shown below:
Let's now increment the value of the integer object by 1:
# Increment a by 1 a = a + 1
When the above code is executed, CPython creates a
new integer object with the value 101 and makes
variable a point to this new integer object. Variable b will
continue to point to the integer object with the
value 100, as shown below:
Python Multiple Inheritance
A class can be derived from more than one superclass in
Python. This is called multiple inheritance.
Syntax :
class SuperClass1:
# features of SuperClass1
class SuperClass2:
# features of SuperClass2 class MultiDerived(SuperClass1,
SuperClass2):
# features of SuperClass1 + SuperClass2 + MultiDerived class
class Mammal:
def mammal_info(self):
print("Mammals can give direct birth.") class
WingedAnimal:
def winged_animal_info(self):
print("Winged animals can flap.")
class Bat(Mammal, WingedAnimal):
pass
# create an object of Bat class
b1 = Bat()
b1.mammal_info()
b1.winged_animal_info()
Output
Mammals can give direct birth.
Winged animals can flap.
Python Operator Overloading