Object-Oriented Programming
Classes and Objects
Python Classes/Objects
• Python is an object oriented programming language.
• Almost everything in Python is an object, with its properties and
methods.
• A Class is like an object constructor, or a "blueprint" for creating
objects.
Create a Class
• To create a class, use the keyword class:
• Create a class named MyClass, with a property named x:
• class MyClass:
x=5
Create Object
• Now we can use the class named MyClass to create objects:
• Create an object named p1, and print the value of x:
• p1 = MyClass()
print(p1.x) O/P: 5
The __init__() Method
• To understand the meaning of classes we have to understand the built-
in __init__() method.
• All classes have a method called __init__(), which is always executed when the
class is being initiated.
• Use the __init__() method to assign values to object properties, or other
operations that are necessary to do when the object is being created:
• Create a class named Person, use the __init__() method to assign values for
name and age:
• class Person:
def __init__(self, name, age):
self.name = name
self.age = age
p1 = Person("John", 36)
print(p1.name)
print(p1.age)
The __init__() method is called automatically every time the class is being used to
create a new object.
Create Methods
• You can create your own methods inside objects.
Methods in objects are functions that belong to the
object.
• Insert a function that prints a greeting, and execute it
on the p1 object:
• class Person:
def __init__(self, name, age):
self.name = name
self.age = age
• def myfunc(self):
print("Hello my name is " + self.name)
p1 = Person("John", 36)
p1.myfunc() O/P:Hello my name is John
The self Parameter
• The self parameter is a reference to the current instance of the
class, and is used to access variables that belong to the class.
• It does not have to be named self, you can call it whatever you
like, but it has to be the first parameter of any function in the
class:
• Use the words mysillyobject and abc instead of self:
• class Person:
def __init__(mysillyobject, name, age):
mysillyobject.name = name
mysillyobject.age = age
def myfunc(abc):
print("Hello my name is " + abc.name)
p1 = Person("John", 36)
p1.myfunc() O/P:Hello my name is John
Modify Object Properties:
• Set the age of p1 to 40:
• p1.age = 40 print(p1.age) O/P: 40
Delete Object Properties
• You can delete properties on objects by using
the del keyword
• Delete the age property from the p1 object:
• del p1.age print(p1.age) O/P: Error
Delete Objects
• You can delete objects by using the del keyword:
• Delete the p1 object:
• del p1 print(p1) O/P: Error
The pass Statement
• class definitions cannot be empty, but if you
for some reason have a class definition with
no content, put in the pass statement to avoid
getting an error.
class Person:
pass
Class Attributes :
• The properties or variables defined inside a
class are called as Attributes.
• An attribute provides information about the
type of data a class contains.
• There are two types of attributes in Python
namely instance attribute and class attribute.
Class attributes are those variables that belong to
a class and whose value is shared among all the
instances of that class. A class attribute remains
the same for every instance of the class.
• class Employee:
name = "Bhavesh Aggarwal“
age = "30"
# instance of the class
emp = Employee()
# accessing class attributes
print("Name of the Employee:", emp.name)
print("Age
Output
• Name of the Employee: Bhavesh Aggarwal
• Age of the Employee: 30
class Employee:
# class attribute
empCount = 0
def __init__(self, name, age):
self.__name = name
self.__age = age
# modifying class attribute
Employee.empCount += 1
print ("Name:", self.__name, ", Age: ", self.__age)
# accessing class attribute
print ("Employee Count:", Employee.empCount)
e1 = Employee("Bhavana", 24)
print()
e2 = Employee("Rajesh", 26)
Instance Variables
• Variables that are unique to each instance
(object) of a class. These are defined
within __init__() method or other instance
methods. Each object maintains its own copy
of instance variables, independent of other
objects.
class Dog:
# Class variable
species = "Canine“
def __init__(self, name, age):
# Instance variables
self.name = name
self.age = age
# Create objects
dog1 = Dog("Buddy", 3)
dog2 = Dog("Charlie", 5)
# Access class and instance variables
print(dog1.species) # (Class variable)
print(dog1.name) # (Instance variable)
print(dog2.name) # (Instance variable)
# Modify instance variables
dog1.name = "Max"
print(dog1.name) # (Updated instance variable)
• Class Variable (species): Shared by all instances of the
class. Changing Dog.species affects all objects, as it's a
property of the class itself.
• Instance Variables (name, age): Defined in the
__init__() method. Unique to each instance (e.g.,
dog1.name and dog2.name are different).
• Accessing Variables: Class variables can be accessed
via the class name (Dog.species) or an object
(dog1.species). Instance variables are accessed via the
object (dog1.name).
• Updating Variables: Changing Dog.species affects all
instances. Changing dog1.name only affects dog1 and
does not impact dog2.
Class Methods vs Static Methods
class Example:
class_variable = "I'm shared across all instances"
def __init__(self, instance_var):
self.instance_var = instance_var
@classmethod
def class_method(cls):
print(f"Class method accessing class variable:
{cls.class_variable}")
return cls("Created via class method")
- Class methods receive the class as the first argument (`cls`)
- Class methods can access and modify class state
@staticmethod
def static_method():
print("Static method can't access class or instance
variables directly")
return "Static result"
def instance_method(self):
print(f"Instance method accessing instance
var: {self.instance_var}")
- Static methods don’t receive any automatic arguments
- Static methods can’t access class or instance state
without explicitly passing them
class MyClass:
class_variable = 10
@classmethod
def get_class_variable(cls):
return cls.class_variable
@classmethod
def create_instance(cls, value):
return cls(value) # Calls the class's __init__ method
def __init__(self, value):
self.instance_variable = value
# Usage
print(MyClass.get_class_variable()) O/P: 10
instance = MyClass.create_instance(20)
print(instance.instance_variable) O/P:20