父类调用
继承:新创建的叫子类,继承的叫父类、超类、基类。子类可以使用父类的属性和函数。
1. 格式:
class SubClass ( BaseClass)
2. 子类重写父类的某个方法后,使用父类方法的一些部分,可以在子类的该方法上:
class Fish:
def __init__(self):
self.x = r.randint(0, 10)
self.y = r.randint(0, 10)
(1) 调用未绑定的父类方法
class Shark(Fish):
def __init__(self):
Fish.__init__(self)
self.hungry = True
(2)使用super函数
class Shark(Fish):
def __init__(self):
super().__init__()
self.hungry = True
3.多重继承
格式:class SubClass ( Base1,Base2,Base3 )
import random as r
class Fish:
def __init__(self):
self.x = r.randint(0, 10)
self.y = r.randint(0, 10)
def move(self):
self.x -= 1
print("我的位置是:",self.x , self.y)
class Goldfish(Fish):
pass
class Carp(Fish):
pass
class Shark(Fish):
def __init__(self):
super().__init__()
self.hungry = True
def eat(self):
if self.hungry:
print("吃货的梦想就是天天有的吃")
self.hungry = False
else :
print("太撑了")

本文深入探讨Python中继承的概念,包括子类如何调用父类的构造函数,使用super函数进行方法调用,以及多重继承的基本语法。通过具体代码示例,读者将能掌握这些关键概念。
14万+

被折叠的 条评论
为什么被折叠?



