Module 12
Module 12
1
© Nex-G Exuberant Solutions Pvt. Ltd.
OOP Terminology
• Class: A user-defined prototype for an object that defines a set of attributes that
characterize any object of the class. The attributes are data members (class variables
and instance variables) and methods, accessed via dot notation.
• Class variable: A variable that is shared by all instances of a class. Class variables are
defined within a class but outside any of the class's methods. Class variables aren't
used as frequently as instance variables are.
• Data member: A class variable or instance variable that holds data associated with a
class and its objects.
• Function overloading: The assignment of more than one behavior to a particular
function. The operation performed varies by the types of objects (arguments) involved.
• Instance variable: A variable that is defined inside a method and belongs only to the
current instance of a class.
• Inheritance : The transfer of the characteristics of a class to other classes that are
derived from it. .
2
© Nex-G Exuberant Solutions Pvt. Ltd.
OOP Terminology
• Instance: An individual object of a certain class. An object obj that belongs to a class
Circle, for example, is an instance of the class Circle.
• Instantiation : The creation of an instance of a class.
• Method : A special kind of function that is defined in a class definition.
• Object : A unique instance of a data structure that's defined by its class. An object
comprises both data members (class variables and instance variables) and methods.
• Operator overloading: The assignment of more than one function to a particular
operator
3
© Nex-G Exuberant Solutions Pvt. Ltd.
What is a Class?
• Data structures like lists and strings are extremely useful, but sometimes they aren’t
enough to represent something you’re trying to implement
• Classes give us the ability to create more complicated data structures that contain
arbitrary content. We can create a Pet class that keeps track of the name and species of
the pet in usefully named attributes called name and species, respectively.
What is an Instance?
• Before we get into creating a class itself, we need to understand an important distinction.
A class is something that just contains structure – it defines how something should be laid
out or structured, but doesn’t actually fill in the content. For example, a Pet class may say
that a pet needs to have a name and a species, but it will not actually say what the pet’s
name or species is.
• This is where instances come in. An instance is a specific copy of the class that does
contain all of the content
4
© Nex-G Exuberant Solutions Pvt. Ltd.
Creating Classes
• The class statement creates a new class definition. The name of the class immediately
follows the keyword class followed by a colon as follows−
• Note: By convention class names are always capitalized.
class ClassName:
'Optional class documentation string'
pass # Pass keyword as a placeholder for body of class
• The class has a documentation string, which can be accessed via ClassName.__doc__
• The body consists of all the component statements defining class members, data
attributes and functions
5
© Nex-G Exuberant Solutions Pvt. Ltd.
Ex-
class Employee:
'Common base class for all employees'
# Class variables
empCount = 0
def __init__(self, name, salary):
# Instance variables
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print(f"Total Employee {Employee.empCount}")
def displayEmployee(self):
print("Name : ", self.name, ", Salary: ", self.salary)
6
© Nex-G Exuberant Solutions Pvt. Ltd.
• The variable empCount is a class variable whose value would be shared among all
instances of a this class.
• This can be accessed as Employee.empCount from inside the class or outside the
class.
• The first method __init__() is a special method, which is called class constructor or
initialization method that Python calls when you create a new instance of this class.
• You declare other class methods like normal functions with the exception that the first
argument to each method is self. Python adds the self argument to the list for you; you
don't need to include it when you call the methods.
7
© Nex-G Exuberant Solutions Pvt. Ltd.
Creating instance objects:
To create instances of a class, you call the class using class name and pass in whatever
arguments
its __init__ method accepts.
"This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
Accessing attributes:
You access the object's attributes using the dot operator with object. Class variable would
be accessed using class name as follows:
emp1.displayEmployee()
emp2.displayEmployee()
print(f"Total Employee {Employee.empCount}”)
8
© Nex-G Exuberant Solutions Pvt. Ltd.
Example
•Now, putting all the concepts together −
class Employee:
'Common base class for all employees'
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print "Total Employee %d" % Employee.empCount
def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
9
© Nex-G Exuberant Solutions Pvt. Ltd.
Namespaces
• class instantiation:
>>> x = MyClass()
>>> print(x.f())
'hello world'
• creates new instance of class
– note x = MyClass vs. x = MyClass()
• ___init__() special method for initialization of object
def __init__(self, realpart, imagpart):
self.r = realpart
self.i = imagpart
• attribute references
• data attributes (C++/Java data members)
– created dynamically
x.counter = 1
while x.counter < 10:
x.counter = x.counter * 2
print(x.counter)
del x.counter
• Called immediately:
x.f()
• can be referenced:
xf = x.f
while True:
print xf()
• object is passed as first argument of function _ 'self'_
– x.f() is equivalent to MyClass.f(x)
• Every Python class keeps following built-in attributes and they can be accessed using
dot operator like any other attribute:
• __dict__ : Dictionary containing the class's namespace.
• __doc__ : Class documentation string or None if undefined.
• __name__: Class name.
• __module__: Module name in which the class is defined. This attribute is "__main__"
in interactive mode.
• __bases__ : A possibly empty tuple containing the base classes, in the order of their
occurrence in the base class list.
16
© Nex-G Exuberant Solutions Pvt. Ltd.
Destroying Objects (Garbage Collection):
• Python deletes unneeded objects (built-in types or class instances) automatically to free
memory space.
• An object's reference count increases when it's assigned a new name or placed in a
container (list, tuple or dictionary). The object's reference count decreases when it's
deleted with del, its reference is reassigned, or its reference goes out of scope. When an
object's reference count reaches zero, Python collects it automatically.
• when the garbage collector destroys an orphaned instance and reclaims its space. But a
class can implement the special method __del__(), called a destructor, that is invoked
when the instance is about to be destroyed. This method might be used to clean up any
non memory resources used by an instance.
17
© Nex-G Exuberant Solutions Pvt. Ltd.
EXAMPLE:
This __del__() destructor prints the class name of an instance that is about to be destroyed:
class Point:
def __init__( self, x=0, y=0):
self.x = x
self.y = y
def __del__(self):
class_name = self.__class__.__name__
print(class_name, “ destroyed“)
pt1 = Point()
pt2 = pt1
pt3 = pt1
print(id(pt1), id(pt2), id(pt3)) # prints the ids of the objects
del pt1
del pt2
del pt3 When the above code is executed, it produces the
following result:
3083401324 3083401324 3083401324
Point destroyed
18
© Nex-G Exuberant Solutions Pvt. Ltd.
Class Inheritance
Instead of starting from scratch, you can create a class by deriving it from a pre existing
class by listing the parent class in parentheses after the new class name.
The child class inherits the attributes of its parent class, and you can use those attributes
as if they were defined in the child class. A child class can also override data members and
methods from the parent.
SYNTAX:
Derived classes are declared much like their parent class; however, a list of base classes
to inherit from are given after the class name:
class SubClassName (ParentClass1, ParentClass2, ...):
'Optional class documentation string’
pass
19
© Nex-G Exuberant Solutions Pvt. Ltd.
EXAMPLE
20
© Nex-G Exuberant Solutions Pvt. Ltd.
c = Child() # instance of child
c.childMethod() # child calls its method
c.parentMethod() # calls parent's method
c.setAttr(200) # again call parent's method
c.getAttr() # again call parent's method
21
© Nex-G Exuberant Solutions Pvt. Ltd.
Overriding Methods:
You can always override your parent class methods. One reason for overriding parent's
methods is because you may want special or different functionality in your subclass.
EXAMPLE:
class Parent: # define parent class
def myMethod(self):
print('Calling parent method’)
class Child(Parent): # define child class
def myMethod(self):
print('Calling child method’)
c = Child() # instance of child
c.myMethod() # child calls overridden method
22
© Nex-G Exuberant Solutions Pvt. Ltd.
Overloading Operators
23
© Nex-G Exuberant Solutions Pvt. Ltd.
Data Hiding:
An object's attributes may or may not be visible outside the class definition. For these cases, you
can name attributes with a double underscore prefix, and those attributes will not be directly visible
to outsiders.
EXAMPLE:
class JustCounter:
__secretCount = 0
def count(self):
self.__secretCount += 1
print(self.__secretCount)
counter = JustCounter()
counter.count()
counter.count()
print(counter.__secretCount)
When the above code is executed, it produces Attribute error
24
© Nex-G Exuberant Solutions Pvt. Ltd.
Python protects those members by internally changing the name to include the class name.
You can access such attributes as object._className__attrName. If you would replace
your last line as following, then it would work for you:
print(counter._JustCounter__secretCount)
25
© Nex-G Exuberant Solutions Pvt. Ltd.
Class Methods
• It is a special type of method that is bound to the class instead of the instance of the
class
• Class methods can access all attributes that are bound to the class itself. E.g., class
variables, other class methods and static methods.
• To define a class method, we use the decorator @classmethod. And like the ‘self’
keyword in normal methods, we use ‘cls’ keyword for class methods.
• On the next slide is an example using the employee class from before:
26
© Nex-G Exuberant Solutions Pvt. Ltd.
Apr 10, 2025
Class Methods
class Employee:
'Common base class for all employees'
# Class variables
empCount = 0
def __init__(self, name, salary):
# Instance variables
self.name = name
self.salary = salary
Employee.empCount += 1
@classmethod
def displayCount(cls):
print(f"Total Employee {cls.empCount}")
def displayEmployee(self):
print("Name : ", self.name, ", Salary: ", self.salary)
27
© Nex-G Exuberant Solutions Pvt. Ltd.
Apr 10, 2025
Static Methods
• It is a special type of method that is similar to a normal function and not bound to the
class or instance at all.
• Static methods cannot access any class attributes or methods.
• To define a static method, we use the decorator @staticmethod. We don’t need to define
‘self’ or ‘cls’ for a static method.
• On the next slide is an example using the employee class from before:
28
© Nex-G Exuberant Solutions Pvt. Ltd.
Apr 10, 2025
Static Methods
class Employee:
'Common base class for all employees'
# Class variables
empCount = 0
def __init__(self, name, salary):
# Instance variables
self.name = name
self.salary = salary
Employee.empCount += 1
@classmethod
def displayCount(cls):
print(f"Total Employee {cls.empCount}")
@staticmethod
def sum(num1, num2):
return num1 + num2
29
© Nex-G Exuberant Solutions Pvt. Ltd.
Apr 10, 2025