https://www.geeksforgeeks.
org/python-classes-and-
objects/
Python Classes and Objects
Last Updated: 31-05-2020
A class is a user-defined blueprint or prototype from which objects are created.
Some points on Python class:
Classes are created by keyword class.
Attributes are the variables that belong to class.
Attributes are always public and can be accessed using dot (.) operator. Eg.:
Myclass.Myattribute
class ClassName:
# Statement-1
.
.
.
# Statement-N
An object consists of :
State/Attribute : It is represented by attributes of an object. It also reflects the properties
of an object.
Behavior/methods : It is represented by methods of an object. It also reflects the
response of an object with other objects.
Identity : It gives a unique name to an object and enables one object to interact with
other objects.
Class child
Identity – name of the child
Attribute – Age/Gendar
Behavior/Methods – Walk, run, Sleep
Declaring Objects (Also called instantiating a class)
All the instances share the attributes and the behavior of the class. But the values of those attributes, i.e. the
state are unique for each object. A single class may have any number of instances.
Child –
Daksh – 12, Boy, walk/run/swim/play cricket
Akshita – 11 Girl, walk/run/read books
# Python program to
# demonstrate instantiating
# a class
class Dog:
# A simple class
# attribute
attr1 = "mamal"
attr2 = "dog"
# A sample method
def fun(self):
print("I'm a", self.attr1)
print("I'm a", self.attr2)
# Driver code
# Object instantiation
Rodger = Dog()
# Accessing class attributes
# and method through objects
print(Rodger.attr1)
Rodger.fun()