[go: up one dir, main page]

0% found this document useful (0 votes)
173 views21 pages

Chapter 9

1) Classes provide a blueprint for creating objects with common attributes and behaviors. 2) To create an object from a class, the class name is used as a function. The __init__() method initializes the object's attributes. 3) Class methods must have self as the first argument to refer to the object instance. Special methods like __init__() and __del__() are automatically called when objects are created and deleted.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
173 views21 pages

Chapter 9

1) Classes provide a blueprint for creating objects with common attributes and behaviors. 2) To create an object from a class, the class name is used as a function. The __init__() method initializes the object's attributes. 3) Class methods must have self as the first argument to refer to the object instance. Special methods like __init__() and __del__() are automatically called when objects are created and deleted.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 21

1

Python Programming
Using Problem Solving Approach

Reema Thareja

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


CHAPTER 9
Classes and Objects

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


Classes and Objects
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. In fact, 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.

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


Creating Objects
Once a class is defined, the next job is to create an object (or instance) of that class. The object can then access class variables
and class methods using the dot operator (.). The syntax to create an object is given as,

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:

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


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 is the
highest level of data protection. 5

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


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 that is added to the
beginning of the parameter list. Moreover, you do not pass a value for this parameter Example:
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 to be
used. For this reason, they are often referred to as instance methods.
6

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


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:

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


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.
8

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


Class Variables And Object Variables - Example

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


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.

Example:

10

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


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:

11

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


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 underscore prefix (__). These variables can be accessed only from within the class and from nowhere outside
the class.
Example:

12

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


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
Example:

13

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


Calling a Class Method from Another Class Method
Example:

14

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


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 attribute.
15

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


Built-in Functions - Example

16

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


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.
17

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


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. For example,

18

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


Class Methods
Class methods are little different from these ordinary methods. First, they are called by a class (not by instance of
the class). Second, the first argument of the classmethod is cls not the self.
Class methods are widely used for factory methods, which instantiate an instance of a class, using different
parameters than those usually passed to the class constructor.
Example:

19

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


Static Methods
Any functionality that belongs to a class, but that does not require the object is placed in the static method. Static
methods are similar to class methods. The only difference is that a static method does not receive any additional
arguments. They are just like normal functions that belong to a class.
A static method does not use the self variable and is defined using a built-in function named staticmethod. Python has a
handy syntax, called a decorator, to make it easier to apply the staticmethod function to the method function definition.
The syntax for using the staticmethod decorator.

20

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.


Static Methods — Example

21

© OXFORD UNIVERSITY PRESS 2017. ALL RIGHTS RESERVED.

You might also like