Discuss / Python / 类的继承和多态

类的继承和多态

Topic source

1,字类可以继承父类的属性和方法,也可以覆盖和新增自己的属性和方法

2,传入的参数是父类、子类还是其他无关的类,只有存在相同的方法,都可以用函数进行调用对应类的方法(多态?),例子:

class A:
    def run(self):
        print('A')

class B(A):
    def run(self):
        print('B')

class X:
    def run(self):
        print('X')

def run_twice(arg):
    arg.run()
    arg.run()

run_twice(A())
#A
#A
run_twice(B())
#B
#B
run_twice(X())
#X
#X

判断实例的类型: 

>>> a = A()
>>> b = B()
>>> isinstance(b, B)
True
>>> isinstance(b, A)
True

  • 1

Reply