Python Learning Week 3

 

Classes and Inheritance in​​ Python

 

Background​​ 

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]​​ 

​​ 

Example1:

class MyClass:​​ 

 i = 12345​​ 

 def f(self):​​ 

 return 'hello world'​​ 

x = MyClass()

print x.i

print x.f()​​ 

Example2:

class Complex:

 ​​ ​​ ​​​​ def __init__(self, realpart, imagpart):

 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ self.r = realpart​​ 

 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ self.i = imagpart​​ 

x = Complex(3.0, -4.5)

print x.r,"  ​​ ​​ ​​ ​​​​ ",x.i​​ 

 

 

Example3:

class Shape:

 ​​ ​​ ​​​​ def __init__(self,x,y):

 ​​ ​​ ​​ ​​ ​​ ​​ ​​​​ 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()

Inheritence 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 + 3 * self.y​​ 

 

Task 1

Create a class​​ name​​ basic_calc​​ with following attributes and methods; Two integers (values are passed with instance creation) Different methods such as​​ addition, subtraction, division, multiplication​​ 

Create another class inherited from​​ basic_calc​​ named​​ s_calc​​ which should have the following additional methods;​​ Factorial, x_power_y,log, ln etc​​ 

  • class child_class(parent_class): ​​ 

  •  ​​ ​​ ​​ ​​ ​​​​ def __init__(self,x):​​ 

  • ​​ #it will modify the _init_ function from parent class​​ 

  • #additional methods can be defined​​ 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Check solution here Python Learning Week 3 (Solution)