Class and Object in Python
Class and Object in Python
Topperworld.in
• The class creates a user-defined data structure, which holds its own data
members and member functions, which can be accessed and used by
creating an instance of that class.
• A class is like a blueprint for an object.
©Topperworld
Python Programming
Example:
class Dog:
sound = "bark"
When an object of a class is created, the class is said to be instantiated. All the
instances share the attributes and the behavior of the class. But the values of
©Topperworld
Python Programming
those attributes, i.e. the state are unique for each object. A single class may
have any number of instances.
Example:
# Python3 program to
# demonstrate instantiating
# a class
class Dog:
# A simple class
# attribute
attr1 = "mammal"
attr2 = "dog"
# A sample method
def fun(self):
print("I'm a", self.attr1)
print("I'm a", self.attr2)
# Object instantiation
Python Programming
Output:
mammal
I'm a mammal
I'm a dog
❖ Self Parameter
Example:
class GFG:
def __init__(self, name, company):
self.name = name
self.company = company
def show(self):
print("Hello my name is " + self.name+" and I" +
" work in "+self.company+".")
©Topperworld
Python Programming
Output:
❖ Pass Statement
Example:
class MyClass:
pass
• Instance variables are for data, unique to each instance and class
variables are for attributes and methods shared by all instances of the
class.
• Instance variables are variables whose value is assigned inside a
constructor or method with self whereas class variables are variables
whose value is assigned in the class.
©Topperworld