Laboratory # 02 Classes and Inheritance
Laboratory # 02 Classes and Inheritance
Laboratory # 02 Classes and Inheritance
The word 'class' can be used when describing the code where the class is defined.
A variable inside a class is known as an Attribute
A function inside a class is known as a method
• A class is like a
• Prototype
• Blue-print
• An object creator
• A class defines potential objects
• What their structure will be
• What they will be able to do
• Objects are instances of a class
• An object is a container of data: attributes
• An object has associated functions: methods
Syntax:
# Defining a class
class class_name:
[statement 1]
[statement 2]
[statement 3] [etc]
Inheritance Syntax:
class child_class(parent_class):
def __init__(self,x):
# it will modify the _init_ function from parent class
# additional methods can be defined here
‘self ’ keyword:
The first argument of every class method, including __init__, is always a reference to the current
instance of the class. By convention, this argument is always named self. In the __init__ method, self
refers to the newly created object; in other class methods, it refers to the instance whose method was
called.
Anytime you create an object of the class, the first thing it does before going on to any other line is it
looks for init function and it calls whatever is written in here. You don’t have to call it explicitly like
any other function.
Example 1:
class MyClass:
i = 12345
def f(self):
return 'hello world'
x = MyClass()
print (x.i)
print (x.f())
Example 2:
class Complex:
def __init__(self, realpart, imagpart):
self.r = realpart
self.i = imagpart
x = Complex(3.0, -4.5)
print (x.r," ",x.i )
Example 3:
class Shape:
def __init__(self,x,y): #The __init__ function always runs first
self.x = x
self.y = y
description = "This shape has not been described yet"
author = "Nobody has claimed to make this shape yet"
def area(self):
return self.x * self.y
def perimeter(self):
return 2 * self.x + 2 * self.y
def describe(self,text):
self.description = text
def authorName(self,text):
self.author = text
def scaleSize(self,scale):
self.x = self.x * scale
self.y = self.y * scale
a=Shape(3,4)
print (a.area())
Inheritance Example:
class Square(Shape):
def __init__(self,x):
self.x = x
self.y = x
class DoubleSquare(Square):
def __init__(self,y):
self.x = 2 * y
self.y = y
def perimeter(self):
return 2 * self.x + 2 * self.y
Module:
A module is a python file that (generally) has only definitions of variables, functions, and classes.
def printdetails(self):
print ("This piano is a/an " + self.height + " foot")
print (self.type, "piano, " + self.age, "years old and costing " +
self.price + " dollars.")