零基础入门学习Python(18):对象(3)继承
这节先介绍一下继承:子类继承基类(父类或超类)
>>> class Parent:
def test(self):
print("I am calling the method of class Parent.")
>>> class Child(Parent): #子类继承基类时,把基类的类名写进子类类名后的括号中
pass
>>> p1 = Parent()
>>> p1.test()
I am calling the method of class Parent.
>>> c1 = Child()
>>> c1.test() #通过子类对象调用基类的方法
I am calling the method of class Parent.
>>> class Child(Parent):
def test(self): #在子类中定义一个跟基类中方法同名的方法
print("Different!I am calling the method of class Child.")
>>> c2 = Child()
>>> c2.test() #子类和基类方法同名时,子类会覆盖基类的方法,即此时调用的是子类中的test()方法
Different!I am calling the method of class Child.
下面是一个基类重写__init__()
方法并被子类继承的示例,为了防止子类也重写__init__()
方法导致的覆盖基类初始化方法而使得一些变量在子类中无法访问的问题,提出了两种解决方法。
1)调用未绑定的基类方法
>>> class Pet:
def __init__(self,name,color):
self.name = name
self.color = color
def action(self):
print("My name is ", self.name," and my color is ", self.color)
>>> class Dog(Pet):
def __init__(self,name,color): #子类也重写了初始化方法,会覆盖基类的初始化方法
Pet.__init__(self,name,color) #在子类的初始化方法中调用未绑定的基类的初始化方法
self.hungry = True
def eat(self):
if self.hungry:
print("I am ", self.name," and I want to eat something.")
self.hungry = False
else:
print("My color is ",self.color," and I am full.")
self.hungry = True
>>> pet1 = Pet('LittleSeven0','red')
>>> pet1.action()
My name is LittleSeven0 and my color is red
>>> dog1 = Dog('LittleSeven','black and white')
>>> dog1.action() #因为调用了基类中的初始化方法,所以name和color实际是在基类中被初始化的
My name is LittleSeven and my color is black and white
>>> dog1.eat()
I am LittleSeven and I want to eat something.
>>> dog1.eat()
My color is black and white and I am full.
>>> dog1.eat()
I am LittleSeven and I want to eat something.
2)使用super()方法,它可以自动帮你找出基类中的初始化方法。但是需要注意的是,如果基类init()方法中除了self还有参数,则调用super()方法时应该写入参数
>>> class Dog(Pet):
def __init__(self,name,color):
super().__init__(name,color) #注意这里一定要写入参数
self.hungry = True
def eat(self):
if self.hungry:
print("I am ", self.name," and I want to eat something.")
self.hungry = False
else:
print("My color is ",self.color," and I am full.")
self.hungry = True
>>> dog2 = Dog('LittleSeven3','white')
>>> dog2.action()
My name is LittleSeven3 and my color is white
>>> dog2.eat()
I am LittleSeven3 and I want to eat something.
最后简单介绍一下多重继承:子类继承基类1、基类2、基类3…
>>> class Parent1:
def fun1(self):
print(" I am class Parent1")
>>> class Parent2:
def fun1(self):
print(" Look! I am class Parent2")
>>> class Parent3:
def fun2(self):
print(" Look! I am class Parent3")
>>> class Child(Parent1,Parent2,Parent3): #多重继承时,把基类依次写到子类类名后面的括号中
pass
>>> c = Child() #子类Child继承的两个基类中有同名的方法
>>> c.fun1() #调用基类中的同名方法时,Python会默认选择第一个继承的基类中的方法
I am class Parent1
>>> c.fun2() #没有同名方法时,则调用基类中相应的方法
Look! I am class Parent3
>>> class ChildTest(Parent2,Parent1,Parent3):
pass
>>> c1 = ChildTest()
>>> c1.fun1() #此处,子类调用的是第一个继承的基类Parent2中的fun1()方法
Look! I am class Parent2