码迷,mamicode.com
首页 > 其他好文 > 详细

class Inheritance

时间:2017-09-18 19:47:56      阅读:184      评论:0      收藏:0      [点我收藏+]

标签:ide   blog   pytho   subclass   inpu   ini   and   def   obj   

技术分享

 

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

标签:ide   blog   pytho   subclass   inpu   ini   and   def   obj   

原文地址:http://www.cnblogs.com/yxi-liu/p/7544611.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!