class Inheritance
阿新 • • 發佈:2017-09-18
check int derived and str example psi lin per
Python Inheritance Syntax
class BaseClass: Body of base class class DerivedClass(BaseClass): Body of derived class
example:
class Polygon: def __init__(self, no_of_sides): self.n = no_of_sides self.sides = [0 for i in range(no_of_sides)] def inputSides(self): self.sides= [float(input("Enter side "+str(i+1)+" : ")) for i in range(self.n)] def dispSides(self): for i in range(self.n): print("Side",i+1,"is",self.sides[i]) class Triangle(Polygon): def __init__(self): Polygon.__init__(self,3) # == super().__init__(self,3) or super(Polygon,self).__init__(self,3)def findArea(self): a, b, c = self.sides # calculate the semi-perimeter s = (a + b + c) / 2 area = (s*(s-a)*(s-b)*(s-c)) ** 0.5 print(‘The area of the triangle is %0.2f‘ %area)
#super(Triangle,obj).func == Polygon.func
super().__init__(3)
is equivalent to Polygon.__init__(self,3)
super(Class,obj) .func--> calling func in base class!
isinstance & issubclass
isinstance()
and issubclass()
are used to check inheritances.
>>> issubclass(Triangle,Polygon) True >>> issubclass(bool,int) True
class Inheritance