我该怎么做?对我来说,使用抽象概念是非常令人困惑的

2024-09-25 10:30:18 发布

您现在位置:Python中文网/ 问答频道 /正文

这是代码

父类

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

子类(从Dog类继承)

class Bulldog(MyDog):
    def run(self, speed):
        return "%s runs %s" % (self.name, speed)

子类(从Dog类继承)

class RussellTerrier(MyDog):
    def run(self, speed):
        return "%s runs %s" % (self.name, speed)

子类(从Dog类继承)

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.

Tags: instancerunnameselfagereturndefruns
1条回答
网友
1楼 · 发布于 2024-09-25 10:30:18

我们有两个父类MyDogMyPet

让我们关注一下MyDog

给出的代码是:

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)

如果我们初始化一个新的BullDog(即

bd = BullDog(name, age)

现在bd具有MyDogrun的所有属性。因此我们可以说bd.eat(); bd.speak("bark"); 等等

如果您想了解有关继承的更多信息,请随时在评论中询问/阅读此文档:https://www.python-course.eu/python3_inheritance.php

相关问题 更多 >