Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
15 views

Python Unit I

Uploaded by

theboby142002
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Python Unit I

Uploaded by

theboby142002
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 32

Unit: I

Object Oriented Python


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 and methods,
accessed via dot notation.
 Class variable − A variable that is shared by all instances of a class. Class variables
are defined within a class but outside any of the class's methods. Class variables are
not used as frequently as instance variables are.
 Data member − A class variable or instance variable that holds data associated with a
class and its objects.
 Function overloading − The assignment of more than one behavior to a particular
function. The operation performed varies by the types of objects or arguments
involved.
 Instance variable − A variable that is defined inside a method and belongs only to the
current instance of a class.
 Inheritance − The transfer of the characteristics of a class to other classes that are
derived from it.
 Instance − An individual object of a certain class. An object obj that belongs to a
class Circle, for example, is an instance of the class Circle.
 Instantiation − The creation of an instance of a class.
 Method − A special kind of function that is defined in a class definition.
 Object − A unique instance of a data structure that's defined by its class. An object
comprises both data members (class variables and instance variables) and methods.
 Operator overloading − The assignment of more than one function to a particular
operator.

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 −
Class ClassName:
'Optional class documentation string'
class_suite
 The class has a documentation string, which can be accessed via ClassName.__doc__.
 The class_suite consists of all the component statements defining class members, data
attributes and functions.
Example

Following is the example of a simple Python class −

class Employee:
'Common base class for all employees'
empCount = 0

def __init__(self, name, salary):


self.name = name
self.salary = salary
Employee.empCount += 1

def displayCount(self):
print "Total Employee %d" % Employee.empCount

def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary
 The variable empCount is a class variable whose value is shared among all instances

of a this class. This can be accessed as Employee.empCount from inside the class or
outside the class.
 The first method __init__() is a special method, which is called class constructor or
initialization method that Python calls when you create a new instance of this class.
 You declare other class methods like normal functions with the exception that the first
argument to each method is self. Python adds the self argument to the list for you; you
do not need to include it when you call the methods.

Creating Instance Objects

To create instances of a class, we call the class using class name and pass in whatever
arguments its __init__ method accepts.

"This would create first object of Employee class"


emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
Accessing Attributes
Access the object's attributes using the dot operator with object. Class variable would be
accessed using class name as follows −

emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount

Now, putting all the concepts together −

#!/usr/bin/python

class Employee:
'Common base class for all employees'
empCount = 0

def __init__(self, name, salary):


self.name = name
self.salary = salary
Employee.empCount += 1

def displayCount(self):
print "Total Employee %d" % Employee.empCount

def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary

"This would create first object of Employee class"


emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print "Total Employee %d" % Employee.empCount
When the above code is executed, it produces the following result −
Name : Zara ,Salary: 2000
Name : Manni ,Salary: 5000
Total Employee 2
we can add, remove, or modify attributes of classes and objects at any time −
emp1.age = 7 # Add an 'age' attribute.
emp1.age = 8 # Modify 'age' attribute.
del emp1.age # Delete 'age' attribute.
Instead of using the normal statements to access attributes, you can use the following
functions −
 The getattr(obj, name[, default]) − to access the attribute of object.
 The hasattr(obj,name) − to check if an attribute exists or not.
 The setattr(obj,name,value) − to set an attribute. If attribute does not exist, then it
would be created.
 The delattr(obj, name) − to delete an attribute.
hasattr(emp1, 'age') # Returns true if 'age' attribute exists
getattr(emp1, 'age') # Returns value of 'age' attribute
setattr(emp1, 'age', 8) # Set attribute 'age' at 8
delattr(empl, 'age') # Delete attribute 'age'

Built-In Class Attributes

Every Python class keeps following built-in attributes and they can be accessed using dot
operator like any other attribute −

 __dict__ − Dictionary containing the class's namespace.


 __doc__ − Class documentation string or none, if undefined.
 __name__ − Class name.
 __module__ − Module name in which the class is defined. This attribute is
"__main__" in interactive mode.
 __bases__ − A possibly empty tuple containing the base classes, in the order of their
occurrence in the base class list.

For the above class let us try to access all these attributes −

#!/usr/bin/python

class Employee:
'Common base class for all employees'
empCount = 0

def __init__(self, name, salary):


self.name = name
self.salary = salary
Employee.empCount += 1

def displayCount(self):
print "Total Employee %d" % Employee.empCount

def displayEmployee(self):
print "Name : ", self.name, ", Salary: ", self.salary

print "Employee.__doc__:", Employee.__doc__


print "Employee.__name__:", Employee.__name__
print "Employee.__module__:", Employee.__module__
print "Employee.__bases__:", Employee.__bases__
print "Employee.__dict__:", Employee.__dict__

When the above code is executed, it produces the following result −

Employee.__doc__: Common base class for all employees


Employee.__name__: Employee
Employee.__module__: __main__
Employee.__bases__: ()
Employee.__dict__: {'__module__': '__main__', 'displayCount':
<function displayCount at 0xb7c84994>, 'empCount': 2,
'displayEmployee': <function displayEmployee at 0xb7c8441c>,
'__doc__': 'Common base class for all employees',
'__init__': <function __init__ at 0xb7c846bc>}

Destroying Objects (Garbage Collection)

Python deletes unneeded objects (built-in types or class instances) automatically to free the
memory space. The process by which Python periodically reclaims blocks of memory that no
longer are in use is termed Garbage Collection.

Python's garbage collector runs during program execution and is triggered when an object's
reference count reaches zero. An object's reference count changes as the number of aliases
that point to it changes.

An object's reference count increases when it is assigned a new name or placed in a container
(list, tuple, or dictionary). The object's reference count decreases when it's deleted with del,
its reference is reassigned, or its reference goes out of scope. When an object's reference
count reaches zero, Python collects it automatically.

a = 40 # Create object <40>


b=a # Increase ref. count of <40>
c = [b] # Increase ref. count of <40>

del a # Decrease ref. count of <40>


b = 100 # Decrease ref. count of <40>
c[0] = -1 # Decrease ref. count of <40>
You normally will not notice when the garbage collector destroys an orphaned instance and
reclaims its space. But a class can implement the special method __del__(), called a
destructor, that is invoked when the instance is about to be destroyed. This method might be
used to clean up any non memory resources used by an instance.

Example
This __del__() destructor prints the class name of an instance that is about to be destroyed −

#!/usr/bin/python

class Point:
def __init__( self, x=0, y=0):
self.x = x
self.y = y
def __del__(self):
class_name = self.__class__.__name__
print class_name, "destroyed"

pt1 = Point()
pt2 = pt1
pt3 = pt1
print id(pt1), id(pt2), id(pt3) # prints the ids of the obejcts
del pt1
del pt2
del pt3
When the above code is executed, it produces following result −

3083401324 3083401324 3083401324


Point destroyed

Note − Ideally, you should define your classes in separate file, then you should import them
in your main program file using import statement.

Class Inheritance
Instead of starting from scratch, you can create a class by deriving it from a preexisting class
by listing the parent class in parentheses after the new class name.

The child class inherits the attributes of its parent class, and you can use those attributes as if
they were defined in the child class. A child class can also override data members and
methods from the parent.
Syntax

Derived classes are declared much like their parent class; however, a list of base classes to
inherit from is given after the class name −

class SubClassName (ParentClass1[, ParentClass2, ...]):


'Optional class documentation string'
class_suite
Example
#!/usr/bin/python

class Parent: # define parent class


parentAttr = 100
def __init__(self):
print "Calling parent constructor"

def parentMethod(self):
print 'Calling parent method'

def setAttr(self, attr):


Parent.parentAttr = attr

def getAttr(self):
print "Parent attribute :", Parent.parentAttr

class Child(Parent): # define child class


def __init__(self):
print "Calling child constructor"

def childMethod(self):
print 'Calling child method'

c = Child() # instance of child


c.childMethod() # child calls its method
c.parentMethod() # calls parent's method
c.setAttr(200) # again call parent's method
c.getAttr() # again call parent's method
When the above code is executed, it produces the following result −
Calling child constructor
Calling child method
Calling parent method
Parent attribute : 200

Similar way, we can derive a class from multiple parent classes as follows −
class A: # define class A
.....

class B: # define class B


.....

class C(A, B): # subclass of A and B


.....
You can use issubclass() or isinstance() functions to check a relationships of two classes and
instances.

 The issubclass(sub, sup) boolean function returns true if the given subclass sub is
indeed a subclass of the superclass sup.
 The isinstance(obj, Class) boolean function returns true if obj is an instance of
class Class or is an instance of a subclass of Class

Overriding Methods
We can always override our parent class methods. One reason for overriding parent's
methods is because we may want special or different functionality in our subclass.
#!/usr/bin/python

class Parent: # define parent class


def myMethod(self):
print 'Calling parent method'

class Child(Parent): # define child class


def myMethod(self):
print 'Calling child method'

c = Child() # instance of child


c.myMethod() # child calls overridden method
When the above code is executed, it produces the following result −

Calling child method

Base Overloading Methods


Following table lists some generic functionality that you can override in your own classes −

Sr.No. Method, Description & Sample Call

1
__init__ ( self [,args...] )
Constructor (with any optional arguments)
Sample Call : obj = className(args)

2
__del__( self )
Destructor, deletes an object
Sample Call : del obj

3
__repr__( self )
Evaluable string representation
Sample Call : repr(obj)

4
__str__( self )
Printable string representation
Sample Call : str(obj)

5
__cmp__ ( self, x )
Object comparison
Sample Call : cmp(obj, x)

Overloading Operators

Suppose you have created a Vector class to represent two-dimensional vectors, what happens
when you use the plus operator to add them

You could, however, define the __add__ method in your class to perform vector addition and
then the plus operator would behave as per expectation −

Example
#!/usr/bin/python

class Vector:
def __init__(self, a, b):
self.a = a
self.b = b

def __str__(self):
return 'Vector (%d, %d)' % (self.a, self.b)

def __add__(self,other):
return Vector(self.a + other.a, self.b + other.b)

v1 = Vector(2,10)
v2 = Vector(5,-2)
print v1 + v2

When the above code is executed, it produces the following result −

Vector(7,8)

Data Hiding
An object's attributes may or may not be visible outside the class definition. You need to
name attributes with a double underscore prefix, and those attributes then are not be directly
visible to outsiders.

Example

#!/usr/bin/python

class JustCounter:
__secretCount = 0

def count(self):
self.__secretCount += 1
print self.__secretCount

counter = JustCounter()
counter.count()
counter.count()
print counter.__secretCount

When the above code is executed, it produces the following result −

1
2
Traceback (most recent call last):
File "test.py", line 12, in <module>
print counter.__secretCount
AttributeError: JustCounter instance has no attribute '__secretCount'

Python protects those members by internally changing the name to include the class name.
You can access such attributes as object._className__attrName. If you would replace your
last line as following, then it works for you −

.........................
print counter._JustCounter__secretCount
When the above code is executed, it produces the following result −
1
2
2

Polymorphism in Python

What is Polymorphism:
The word polymorphism means having many forms. In programming, polymorphism
means the same function name (but different signatures) being used for different types. The
key difference is the data types and number of arguments used in function.
Example of inbuilt polymorphic functions:

# Python program to demonstrate in-built poly-

# morphic functions

# len() being used for a string

print(len("geeks"))

# len() being used for a list

print(len([10, 20, 30]))

Output:
5
3

Examples of user-defined polymorphic functions:

# A simple Python function to demonstrate

# Polymorphism

def add(x, y, z = 0):

return x + y+z

# Driver code

print(add(2, 3))

print(add(2, 3, 4))

Output:
5
9

Polymorphism with class methods:


The below code shows how Python can use two different class types, in the same way. We
create a for loop that iterates through a tuple of objects. Then call the methods without
being concerned about which class type each object is. We assume that these methods
actually exist in each class.

class India():
def capital(self):

print("New Delhi is the capital of India.")

def language(self):

print("Hindi is the most widely spoken language of India.")

def type(self):

print("India is a developing country.")

class USA():

def capital(self):

print("Washington, D.C. is the capital of USA.")

def language(self):

print("English is the primary language of USA.")

def type(self):

print("USA is a developed country.")

obj_ind = India()

obj_usa = USA()

for country in (obj_ind, obj_usa):

country.capital()

country.language()

country.type()

Output:
New Delhi is the capital of India.
Hindi is the most widely spoken language of India.
India is a developing country.
Washington, D.C. is the capital of USA.
English is the primary language of USA.
USA is a developed country.

Polymorphism with Inheritance:

In Python, Polymorphism lets us define methods in the child class that have the
same name as the methods in the parent class. In inheritance, the child class inherits the
methods from the parent class. However, it is possible to modify a method in a child class
that it has inherited from the parent class. This is particularly useful in cases where the
method inherited from the parent class doesn’t quite fit the child class. In such cases, we re-
implement the method in the child class. This process of re-implementing a method in the
child class is known as Method Overriding.

class Bird:

def intro(self):

print("There are many types of birds.")

def flight(self):

print("Most of the birds can fly but some cannot."

class sparrow(Bird):

def flight(self):

print("Sparrows can fly.")

class ostrich(Bird):

def flight(self):
print("Ostriches cannot fly.")

obj_bird = Bird()

obj_spr = sparrow()

obj_ost = ostrich()

obj_bird.intro()

obj_bird.flight()

obj_spr.intro()

obj_spr.flight()

obj_ost.intro()

obj_ost.flight()

Output:
There are many types of birds.
Most of the birds can fly but some cannot.
There are many types of birds.
Sparrows can fly.
There are many types of birds.
Ostriches cannot fly.

Encapsulation in Python

Encapsulation is one of the fundamental concepts in object-oriented programming


(OOP). It describes the idea of wrapping data and the methods that work on data within one
unit. This puts restrictions on accessing variables and methods directly and can prevent the
accidental modification of data. To prevent accidental change, an object’s variable can only
be changed by an object’s method. Those types of variables are known as private
variables.
A class is an example of encapsulation as it encapsulates all the data that is member
functions, variables, etc.
Consider a real-life example of encapsulation, in a company, there are different
sections like the accounts section, finance section, sales section etc. The finance section
handles all the financial transactions and keeps records of all the data related to finance.
Similarly, the sales section handles all the sales-related activities and keeps records of all
the sales. Now there may arise a situation when for some reason an official from the
finance section needs all the data about sales in a particular month. In this case, he is not
allowed to directly access the data of the sales section. He will first have to contact some
other officer in the sales section and then request him to give the particular data. This is
what encapsulation is. Here the data of the sales section and the employees that can
manipulate them are wrapped under a single name “sales section”. Using encapsulation also
hides the data. In this example, the data of the sections like sales, finance, or accounts are
hidden from any other section.

Python Assert Statement

What is Assertion?
Assertions are statements that assert or state a fact confidently in your program. For example,
while writing a division function, you're confident the divisor shouldn't be zero, you assert
divisor is not equal to zero.

Assertions are simply boolean expressions that check if the conditions return true or not. If it
is true, the program does nothing and moves to the next line of code. However, if it's false,
the program stops and throws an error.

It is also a debugging tool as it halts the program as soon as an error occurs and displays it.

We can be clear by looking at the flowchart below:


Python assert Statement
Python has built-in assert statement to use assertion condition in the
program. assert statement has a condition or expression which is supposed to be always true.
If the condition is false assert halts the program and gives an AssertionError.
Syntax for using Assert in Pyhton:

assert <condition>

assert <condition>,<error message>

In Python we can use assert statement in two ways as mentioned above.


1. assert statement has a condition and if the condition is not satisfied the program will stop and
give AssertionError.
2. assert statement can also have a condition and a optional error message. If the condition is
not satisfied assert stops the program and gives AssertionError along with the error message.
Example 1: Using assert without Error Message

def avg(marks):
assert len(marks) != 0
return sum(marks)/len(marks)

mark1 = []
print("Average of mark1:",avg(mark1))
Run Code
When we run the above program, the output will be:

AssertionError

We got an error as we passed an empty list mark1 to assert statement, the condition became
false and assert stops the program and give AssertionError.
Now let's pass another list which will satisfy the assert condition and see what will be our
output.
Example 2: Using assert with error message
def avg(marks):
assert len(marks) != 0,"List is empty."
return sum(marks)/len(marks)

mark2 = [55,88,78,90,79]
print("Average of mark2:",avg(mark2))

mark1 = []
print("Average of mark1:",avg(mark1))
Run Code

When we run the above program, the output will be:

Average of mark2: 78.0


AssertionError: List is empty.

Decorators in Python
Decorators are a very powerful and useful tool in Python since it allows programmers to
modify the behaviour of a function or class. Decorators allow us to wrap another function
in order to extend the behaviour of the wrapped function, without permanently modifying
it. But before diving deep into decorators let us understand some concepts that will come in
handy in learning the decorators.
First Class Objects
In Python, functions are first class objects which means that functions in Python can
be used or passed as arguments.
Properties of first class functions:
 A function is an instance of the Object type.
 You can store the function in a variable.
 You can pass the function as a parameter to another function.
 You can return the function from a function.
 You can store them in data structures such as hash tables, lists, …
Consider the below examples for better understanding.
Example 1: Treating the functions as objects.

# Python program to illustrate functions

# can be treated as objects

def shout(text):

return text.upper()

print(shout('Hello'))

yell = shout

print(yell('Hello'))

Output:
HELLO
HELLO
In the above example, we have assigned the function shout to a variable. This will not call
the function instead it takes the function object referenced by a shout and creates a second
name pointing to it, yell.
Example 2: Passing the function as an argument

# Python program to illustrate functions

# can be passed as arguments to other functions

def shout(text):

return text.upper()

def hint(text):
return text.lower()

def greet(func):

# storing the function in a variable

greeting = func("""Hi, I am created by a function passed as an argument.""")

print (greeting)

greet(shout)

greet(hint)

Output:

HI, I AM CREATED BY A FUNCTION PASSED AS AN ARGUMENT.

hi, i am created by a function passed as an argument.

In the above example, the greet function takes another function as a parameter (shout and
hint in this case). The function passed as an argument is then called inside the function
greet.

Generators in Python

Generator-Function: A generator-function is defined like a normal function, but whenever


it needs to generate a value, it does so with the yield keyword rather than return. If the body
of a def contains yield, the function automatically becomes a generator function.

# A generator function that yields 1 for first time,

# 2 second time and 3 third time

def simpleGeneratorFun():

yield 1
yield 2

yield 3

# Driver code to check above generator function

for value in simpleGeneratorFun():

print(value)

Output
1
2
3

Generator-Object : Generator functions return a generator object. Generator objects


are used either by calling the next method on the generator object or using the generator
object in a “for in” loop (as shown in the above program).

# A Python program to demonstrate use of

# generator object with next()

# A generator function

def simpleGeneratorFun():

yield 1

yield 2

yield 3
# x is a generator object

x = simpleGeneratorFun()

# Iterating over the generator object using next

print(next(x)) # In Python 3, __next__()

print(next(x))

print(next(x))

Output
1
2
3
So a generator function returns an generator object that is iterable, i.e., can be used as
an Iterators . As another example, below is a generator for Fibonacci Numbers.

# A simple generator for Fibonacci Numbers

def fib(limit):

# Initialize first two Fibonacci Numbers

a, b = 0, 1

# One by one yield next Fibonacci Number

while a < limit:

yield a

a, b = b, a + b

# Create a generator object


x = fib(5)

# Iterating over the generator object using next

print(next(x)) # In Python 3, __next__()

print(next(x))

print(next(x))

print(next(x))

print(next(x))

# Iterating over the generator object using for

# in loop.

print("\nUsing for in loop")

for i in fib(5):

print(i)

Output
0
1
1
2
3
Using for in loop
0
1
1
2
3
Iterators in Python
Iterator in Python is an object that is used to iterate over iterable objects like lists, tuples,
dicts, and sets. The iterator object is initialized using the iter() method. It uses
the next() method for iteration.
1. __iter__(): The iter() method is called for the initialization of an iterator. This returns
an iterator object
2. __next__(): The next method returns the next value for the iterable. When we use a for
loop to traverse any iterable object, internally it uses the iter() method to get an iterator
object, which further uses the next() method to iterate over. This method raises a
StopIteration to signal the end of the iteration.
Python iter() Example

string = "GFG"

ch_iterator = iter(string)

print(next(ch_iterator))

print(next(ch_iterator))

print(next(ch_iterator))

Output :
G
F
G

Example 1: Creating and looping over an iterator using iter() and next()

Below is a simple Python custom iterator that creates an iterator type that iterates from 10
to a given limit. For example, if the limit is 15, then it prints 10 11 12 13 14 15. And if the
limit is 5, then it prints nothing.

# A simple Python program to demonstrate


# working of iterators using an example type

# that iterates from 10 to given value

# An iterable user defined type

class Test:

# Constructor

def __init__(self, limit):

self.limit = limit

# Creates iterator object

# Called when iteration is initialized

def __iter__(self):

self.x = 10

return self

# To move to next element. In Python 3,

# we should replace next with __next__

def __next__(self):

# Store current value ofx

x = self.x

# Stop iteration if limit is reached


if x > self.limit:

raise StopIteration

# Else increment and return old value

self.x = x + 1;

return x

# Prints numbers from 10 to 15

for i in Test(15):

print(i)

# Prints nothing

for i in Test(5):

print(i)

Output :
10
11
12
13
14
15

Inheritance in Python
Inheritance is the capability of one class to derive or inherit the properties from another
class.

Benefits of inheritance are:


 It represents real-world relationships well.
 It provides the reusability of a code. We don’t have to write the same code again and
again. Also, it allows us to add more features to a class without modifying it.
 It is transitive in nature, which means that if class B inherits from another class A, then
all the subclasses of B would automatically inherit from class A.

Python Inheritance Syntax

Class BaseClass:
{Body}
Class DerivedClass(BaseClass):
{Body}
Creating a Parent Class
Creating a Person class with Display methods.

# A Python program to demonstrate inheritance

class Person(object):

# Constructor

def __init__(self, name, id):

self.name = name

self.id = id

# To check if this person is an employee

def Display(self):

print(self.name, self.id)
# Driver code

emp = Person("Satyam", 102) # An Object of Person

emp.Display()

Output:
Satyam 102
Creating a Child Class
Here Emp is another class which is going to inherit the properties of the Person class(base
class).
class Emp(Person):

def Print(self):

print("Emp class called")

Emp_details = Emp("Mayank", 103)

# calling parent class function

Emp_details.Display()

# Calling child class function

Emp_details.Print()

Output:
Mayank 103
Emp class called
Example of Inheritance in Python

# A Python program to demonstrate inheritance

# Base or Super class. Note object in bracket.

# (Generally, object is made ancestor of all classes)

# In Python 3.x "class Person" is


# equivalent to "class Person(object)"

class Person(object):

# Constructor

def __init__(self, name):

self.name = name

# To get name

def getName(self):

return self.name

# To check if this person is an employee

def isEmployee(self):

return False

# Inherited or Subclass (Note Person in bracket)

class Employee(Person):

# Here we return true

def isEmployee(self):

return True

# Driver code

emp = Person("Geek1") # An Object of Person

print(emp.getName(), emp.isEmployee())
emp = Employee("Geek2") # An Object of Employee

print(emp.getName(), emp.isEmployee())

Output:
Geek1 False
Geek2 True

What is object class?

Like the Java Object class, in Python (from version 3. x), the object is the root of all
classes.
 In Python 3.x, “class Test(object)” and “class Test” are same.
 In Python 2. x, “class Test(object)” creates a class with the object as a parent (called a
new-style class), and “class Test” creates an old-style class (without an objecting
parent).

Subclassing (Calling constructor of parent class)

A child class needs to identify which class is its parent class. This can be done by
mentioning the parent class name in the definition of the child class.

Eg: class subclass_name (superclass_name):

# Python code to demonstrate how parent constructors

# are called.

# parent class

class Person(object):

# __init__ is known as the constructor

def __init__(self, name, idnumber):


self.name = name

self.idnumber = idnumber

def display(self):

print(self.name)

print(self.idnumber)

# child class

class Employee(Person):

def __init__(self, name, idnumber, salary, post):

self.salary = salary

self.post = post

# invoking the __init__ of the parent class

Person.__init__(self, name, idnumber)

# creation of an object variable or an instance

a = Employee('Rahul', 886012, 200000, "Intern")

# calling a function of the class Person using its instance

a.display()

Output:
Rahul
886012
‘a’ is the instance created for the class Person. It invokes the __init__() of the referred
class. You can see ‘object’ written in the declaration of the class Person. In Python, every
class inherits from a built-in basic class called ‘object’. The constructor i.e. the ‘__init__’
function of a class is invoked when we create an object variable or an instance of the class.
The variables defined within __init__() are called the instance variables or objects. Hence,
‘name’ and ‘idnumber’ are the objects of the class Person. Similarly, ‘salary’ and ‘post’ are
the objects of the class Employee. Since the class Employee inherits from class Person,
‘name’ and ‘idnumber’ are also the objects of class Emplo yee.

You might also like