OOPs IN PYTHON-NOTES-1
OOPs IN PYTHON-NOTES-1
Object: Any entity that has state and behaviour is known as an object.
For Example, a chair, pen, table, keyboard, bike, etc. It can be physical or logical.
An Object can be defined as an instance of a class.
An object contains an address and takes up some space in memory.
Class: Collection of objects is called class. It is a logical entity.
1
A class can also be defined as a blueprint from which you can create an individual object.
Class doesn't consume any space.
Classes are defined by using the class keyword, followed by the ClassName and a colon.
Class definitions must be executed before they have any effect.
In practice, the statements inside a class definition will usually be function definitions, but few other statements
are allowed.
Methods are a special kind of function that is defined within a class.
3
The self
Class methods must have an extra first parameter in the method definition.
We do not give a value for this parameter when we call the method, Python provides it.
Note: The __init__() function is called automatically every time the class is being used to create a new object.
4
Class Objects
An Object is an instance of a Class.
A class is like a blueprint while an instance is a copy of the class with actual values.
Example: You can have many dogs to create many different instances, but without the class as a guide,
you would be lost, not knowing what information is required.
State: It is represented by the attributes of an object. It also reflects the properties of an object.
Behaviour: It is represented by the methods of an object. It also reflects the response of an object to other
objects.
5
Declaring Objects (Also called instantiating a class)
When an object of a class is created, the class is said to be instantiated.
All the instances(objects) share the attributes and the behaviour of the class.
But the state/values of those attributes are unique for each object.
A single class may have any number of instances(objects).
Example:
6
Python Classes/Objects
Python is an object-oriented programming language.
Create Object: Now we can use the class named MyClass to create objects:
7
8
9
10
Figure: Object diagram for Mobile class with data attributes and methods.
11
Create a class named Person, use the __init__() function to assign values for name and age:
12
13