Classes and Objects
Classes and Objects
y.
Python-Class & Object
ud
st
ty
si
er
iv
un
Introduction
• Python has been an object-oriented language
in
since it existed. Because of this, creating and
y.
ud
using classes and objects are downright easy.
st
• This chapter helps you become an expert in
ty
si
using Python's object-oriented programming
er
support.
iv
un
Overview of OOP Terminology
• Class:A user-defined prototype for an object that defines a set of
attributes that characterize any object of the class. The attributes are data
members (class variables and instance variables) and methods, accessed
via dot notation.
in
• Class variable: A variable that is shared by all instances of a class. Class
y.
variables are defined within a class but outside any of the class's methods.
ud
Class variables are not used as frequently as instance variables are.
st
• Instance variable: A variable that is defined inside a method and belongs
ty
only to the current instance of a class.
•
si
Data member: A class variable or instance variable that holds data
er
associated with a class and its objects.
iv
in
a class to other classes that are derived from it.
y.
• Function overloading: The assignment of more
ud
st
than one behavior to a particular function. The
ty
operation performed varies by the types of
si
er
objects or arguments involved.
iv
y.
in
Creating Classes
• The class statement creates a new class definition. The name of the class
immediately follows the keyword class followed by a colon as follows −
in
y.
ud
st
ty
si
er
iv
un
un
iv
er
si
ty
st
ud
y.
in
Creating Instance Objects
in
class"
y.
ud
emp1 = Employee("Zara", 2000)
st
• "This would create second object of Employee
ty
class“ si
er
iv
• emp1.displayEmployee()
in
• emp2.displayEmployee()
y.
ud
• print "Total Employee %d" % Employee.empCount
st
ty
si
er
iv
un
Public and private member in class
in
y.
ud
st
ty
si
er
iv
un
un
iv
er
si
ty
st
ud
y.
in
un
iv
er
si
ty
st
ud
y.
in
Destroying Objects (Garbage
Collection)
• Python deletes unneeded objects (built-in
in
types or class instances) automatically to free
y.
ud
the memory space.
st
• The process by which Python periodically
ty
si
reclaims blocks of memory that no longer are
er
in use is termed Garbage Collection.
iv
un
Example
class Point:
def __init__( self, x=0, y=0):
in
self.x = x
y.
self.y = y
ud
def __del__(self):
st
class_name = self.__class__.__name__
ty
print class_name, "destroyed"
si
pt1 = Point() er
pt2 = pt1
iv
pt3 = pt1
un