这是代码
class MyPet:
dogs = []
def __init__(self, dogs):
self.dogs = dogs
class MyDog:
species = 'mammal' # Class Attribute
def __init__(self, name, age): # Initializer / Instance attributes
self.name = name
self.age = age
def description(self): # Instance Method 1
return self.name, self.age
def speak(self, sound): # Instance Method 2
return "%s says %s" % (self.name, sound)
def eat(self): # Instance Method 3
self.is_hungry = False
class Bulldog(MyDog):
def run(self, speed):
return "%s runs %s" % (self.name, speed)
class RussellTerrier(MyDog):
def run(self, speed):
return "%s runs %s" % (self.name, speed)
class SiberianHusky(MyDog):
def run(self, speed):
return "%s runs %s" % (self.name, speed)
输出应如下所示:
These are my 3 dogs namely:
Justin runs at the speed of 5.
Drake runs at the speed of 6.
Kanye runs at the speed of 7.
我们有两个父类
MyDog
和MyPet
让我们关注一下
MyDog
给出的代码是:
现在让我们看一个子类(斗牛犬)
如果我们初始化一个新的
BullDog
(即现在
bd
具有MyDog
和run
的所有属性。因此我们可以说bd.eat(); bd.speak("bark");
等等如果您想了解有关继承的更多信息,请随时在评论中询问/阅读此文档:https://www.python-course.eu/python3_inheritance.php
相关问题 更多 >
编程相关推荐