Slide_7
Slide_7
Classes and objects are the two main aspects of object oriented programming. In fact, a class is the basic
building block in Python. A class creates a new type and object is an instance (or variable) of the class.
Classes provides a blueprint or a template using which objects are created.
1
Object
•Object is an identifiable entity with some characteristics and behavior.
•Orange is an object. Its characteristics are: it is orange in color and is spherical; its behavior is it is juicy
and it tastes sweet sour.
•While programming using OOP approach, the characteristics are represented by its data, and the
behavior is represented by its associated functions.
•Thus, in OOP, objects represents an entity that can store data and has its interface through functions.
•Consider an example of traffic flow at red light crossing. Using procedural programming, the problem
will be viewed in terms of working happening in the traffic flow i.e. moving, halting, turning etc.
•The OOP aims at objects and their interface. So with OOP, the problem will be viewed as in terms of
cars, trucks, buses, taxis etc.
Class
•A Class is a group of objects that share common properties and relationships.
•In the earlier example, cars be identified as objects. They have characteristics like: steering wheel,
seats, motor, brakes etc. and their behavior is mobility.
•Car however is not an object, it is a class. Wagon R is an object of class type Car. Car further is
subclass of class automobiles which is again subclass of vehicles.
•So, object is basically an instance of class.
•The OOP approach is based on certain concepts that help in overcoming the drawbacks of
conventional programming approaches.These general concepts are :
•1) Data abstraction
•2) Data Encapsulation
•3) Modularity
•4) Inheritance
•5) Polymorphism
Classes and Objects
In Python, everything is an object or an instance of some class. For example, all integer variables that we define in
our program are actually instances of class int. Similarly, all string variables are objects of class string. Recall
that we had used string methods using the variable name followed by the dot operator and the method name.
We have already studied that we can find out the type of any object using the type() function.
Defining Classes
the statement in the definition can be: sequential, decision control statement and can even include function
definition
Variable defined are called : class variables
Functions defined inside a class: class methods
Together they are called: class members
4
Creating an object or instance of a class is known as class instantiation. From the syntax, we can see that class
instantiation uses function notation. Using the syntax, an empty object of a class is created.Thus, we see that
in Python, to create a new object, call a class as if it were a function.The syntax for accessing a class member through
the class object is
Example:
5
Data Abstraction and Hiding through Classes
Classes provide methods to the outside world to provide the functionality of the object or to manipulate the
object's data. Any entity outside the world does not know about the implementation details of the class or
that method.
Data encapsulation, also called data hiding organizes the data and methods into a structure that prevents
data access by any function (or method) that is not specified in the class. This ensures the integrity of the data
contained in the object.
Encapsulation defines different access levels for data variables and member functions of the class. These
access levels specifies the access rights for example,
• Any data or function with access level public can be accessed by any function belonging to any class. This is
the lowest level of data protection.
• Any data or function with access level private can be accessed only by the class in which it is declared. This
6
is
the highest level of data protection.
Class Method And Self Argument
Class methods (or functions defined in the class) are exactly same as ordinary
functions that we have been defining so far with just one small difference. Class
methods must have the first argument named as self. This is the first argument
Example:
that is added to the beginning of the parameter list. Moreover, you do not pass a
value for this parameter when you call the method. Python provides its value
automatically. The self argument refers to the object itself. That is, the object
that has called the method. This means that even if a method that takes no
arguments, should be defined to accept the self. Similarly, a function defined to
accept one parameter will actually take two- self and the parameter, so on and
so forth.
Since, the class methods uses self, they require an object or instance of the class 7
to be used. For this reason, they are often referred to as instance methods.
The __init__() Method (The Class Constructor)
The __init__() method has a special significance in Python classes. The __init__() method is automatically
executed when an object of a class is created. The method is useful to initialize the variables of the class
object. Note the __init__() is prefixed as well as suffixed by double underscores.
Example:
-Here, the __init__() method accepts one argument val.
Like any other class method, the first argument has to
be self.
-In the __init__() method we define a variable as self.val
(same name as in argument list)
-Though names are same, they are entirely different
variables where, the self.val belongs to the newly
created object.
8
Class Variables And Object Variables
Basically, these variables are of two types- class variables and object variables. Class variables are owned by the
class and object variables are owned by each object. What this specifically means can be understood using
following points.
• If a class has n objects, then there will be n separate copies of the object variable as each object will have its
own object variable.
• The object variable is not shared between objects.
• A change made to the object variable by one object will not be reflected in other objects.
If a class has one class variable, then there will be one copy only for that variable. All the objects of that class
will share the class variable.
• Since there exists a single copy of the class variable, any change made to the class variable by an object will
be reflected to all other objects. 9
Class Variables And Object Variables - Example
-Here, we have a class varable, class_var which is shared by all the three objects of the class. It is initialized to zero and
each time an object is created, the class_var is incremented by 1.
-Since the variable is shared by all the objects, changes made to class_var by one object is reflected in other objects as
well.
Then we have object vaiable which is unique for every object. When an object is created and the __init__ method is
called, the object variable is initialized. The object variable belongs to only a particular object
10
The __del__() Method
The __del__() method does just the opposite work. The __del__() method is automatically called when an
object is going out of scope. This is the time when object will no longer be used and its occupied resources
are returned back to the system so that they can be reused as and when required. You can also explicitly do
the same using the del keyword.
11
Other Special Methods
• __repr__(): __ The __repr__() function is a built-in function with syntax repr(object). It returns a string
representation of an object.The function works on any object, not just class instances.
• __cmp__():The __cmp__() function is called to compare two class objects.
• __len__(): The __len__() function is a built-in function that has the syntax, len(object). It returns the length of
an object.
Example:
12
Public and Private Data Members
Public variables are those variables that are defined in the class and can be accessed from anywhere in the
program, of course using the dot operator. Private variables, on the other hand, are those variables that are
defined in the class with a double score prefix (__). These variables can be accessed only from within the class
and from nowhere outside the class.
13
Private Methods
Like private attributes, you can even have private methods in your class. Usually, we keep those methods as
private which have implementation details. So like private attributes, you should also not use private method
from anywhere outside the class. However, if it is very necessary to access them from outside the class, then
they are accessed with a small difference. A private method can be accessed using the object name as well as
the class name from outside the class. The syntax for accessing the private method in such a case would be.
objectname._classname__privatemethodname
In-order to access the private method the following thing can
be done
objectname._classname__privatemethod
14
Calling a Class Method from Another Class Method
Example:
15
Built-in Functions To Check, Get, Set And Delete Class Attributes
hasattr(obj,name):The function is used to check if an object possess the attribute or not.
getattr(obj, name[, default]): The function is used to access or get the attribute of object. Since getattr() is a
built-in function and not a method of the class, it is not called using the dot operator. Rather, it takes the
object as its first parameter. The second parameter is the name of the variable as a string, and the optional
third parameter is the default value to be returned if the attribute does not exist. If the attribute name does
not exist in the object's namespace and the default value is also not specified, then an exception will be raised.
Note that, getattr(obj, 'var') is same as writing obj.var. However, you should always try to use the latter variant.
setattr(obj,name,value): The function is used to set an attribute of the object. If attribute does not exist, then
it would be created. The first parameter of the setattr() function is the object, the second parameter is the
name of the attribute and the third is the new value for the specified attribute.
delattr(obj, name): The function deletes an attribute. Once deleted, the variable is no longer a class or object
16
attribute.
Built-in Functions - Example
17
Built-in Class Attributes
.__dict__: The attributes gives a dictionary containing the class's or Example:
object's (with whichever it is accessed) namespace.
.__doc__: The attribute gives the class documentation string if
specified. In case the documentation string is not specified, then the
attribute returns None.
.__name__:The attribute returns the name of the class.
.__module__: The attribute gives the name of the module in which
the class (or the object) is defined.
.__bases__: Used in inheritance to return the base classes in the
order of their occurrence in the base class list.
18
Garbage Collection (Destroying Objects)
Python performs automatic garbage collection. This means that it deletes all the objects (built-in types or user
defined like class objects) automatically that are no longer needed and that have gone out of scope to free the
memory space. The process by which Python periodically reclaims unwanted memory is known as garbage
collection.
Python's garbage collector runs in the background during program execution. It immediately takes action (of
reclaiming memory) as soon as an object's reference count reaches zero.
19