题目:Python 中的继承、多态和封装
涉及问题:
Python 中如何实现多继承,会有什么问题?
Python 中的多态与静态方法有什么区别?
答案要点如下:
class Father(object): # object 是最基础的一个类,和 JAVA 中的 Object 是一样的
pass
class Chile(Father): # 继承 Father 类
pass
class Father(object):
f_out = "123"
def __init__(self, f):
print("father class")
self.f = f
class Child_1(Father):
pass
class Child_2(Father):
# 如果子类中不重写 __init__ 方法,会默认调用父类中的 __init__ 方法
# 但是如果重写后,则不会自动调用父类中的 __init__ 方法,需要手动来调用
def __init__(self):
# 如果子类在初始化参数时,没有父类的参数,则子类不再有父类拥有的实例属性
# 但类属性仍然会被继承
print("child class")
print(self.f_out)
# 如果想调用父类
# super(Child_2, self).__init__("123")
# c1 = Child_1() # 如果不传参会报错说接受一个参数,这里就已经说明在调用父类的 __init__
c1 = Child_1("123") # 输出 father class,且必须传入一个参数
print(c1.f) # 得到 123
c2 = Child_2() # 不接受参数,因为子类中没有参数
# 输出 child class 123
# print(c2.f) # 报错,找不到 attribute f
# python2
super(Child, self).父类方法(*args, **kw)
# python3
super().父类方法(*args, **kw)
class Father():
pass
class Mother():
pass
class Child(Father, Mother):
pass
class Base(object):
def __init__(self):
print("enter base")
print('leave base')
class A(Base):
def __init__(self):
print('enter A')
super(A, self).__init__()
print('leave A')
class B(Base):
def __init__(self):
print('enter B')
super(B, self).__init__()
print('leave B')
class C(A,B):
def __init__(self):
print('enter C')
super(C, self).__init__()
print('leave C')
c = C()
# 输出结果如下
‘’‘
enter C
enter A
enter B
enter base
leave base
leave B
leave A
leave C
’‘’
class Test(object):
def __init__(self, name, age, sex):
self.__name = name
self._age = age
self.sex = sex
t = Test("Demon", 18, 'M')
# print(t.__name) # 'Test' object has no attribute '__name'
print(t._Test__name) # 可以这样访问到,但不要这样做
print(t._age) # 18
print(t.sex) # M
class Animal(object):
def run(self):
print('Animal run')
# 定义一个 Animal 的子类
class Dog(Animal):
def run(self):
print('Dog run')
# 定义一个类似 Animal 的类
class Like_Animal(object):
# 同样具有 run() 方法
def run(self):
print('I can run too!!!')
# 定义一个方法,参数是实例对象 ,根据参数来调用对应的 run() 方法
# 也就是我们说的多态
def start_run(run_obj):
run_obj.run()
# 传入一个 Animal 实例对象
start_run(Animal())
# 传入一个 Dog 实例对象
start_run(Dog())
# 传入一个 类Animal 实例对象
start_run(Like_Animal())
扩展:
愿关注我们的人都能找到
属于自己的皮球