class Inheritance

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了class Inheritance相关的知识,希望对你有一定的参考价值。

技术分享

 

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的主要内容,如果未能解决你的问题,请参考以下文章

markdown JS:Class&Prototypal Inheritance

Cpp Chapter 13: Class Inheritance Part1

[Dart] Understand Classes and Inheritance in Dart

[TypeScript] Sharing Class Behavior with Inheritance in TypeScript

Week 5: Object Oriented Programming 9. Classes and Inheritance Exercise: int set

Hibernate继承映射(@Inheritance)