为了账号安全,请及时绑定邮箱和手机立即绑定

Python3:类组合和派生方法

Python3:类组合和派生方法

跃然一笑 2023-08-22 15:57:16
早上好,我正在尝试这样的事情:class Fish:  def __init__(self, name):    self.name = name  def swim(self):    print(self.name,"is swimming!")我的建议是将课程扩展到 Aquarium,其中包含鱼类字典:class Aquarium(Fish):  def __init__(self, **kwargs):    self.fishes ={}    for _, name in kwargs.items():      self.fishes[name] = Fish.__init__(self,name)    def how_many(self):    print("In acquarium there are",len(self.fishes),"fishes")    def all_swimming(self):#???是否可以实现像 Aquarium.swim() 这样的东西来使用插入的所有类的方法?我尝试过,但结果它只打印出最后插入的鱼。有什么建议吗?如何在 Aquarium() 中收集许多 Fish()?有更好的方法吗?
查看完整描述

2 回答

?
九州编程

TA贡献1785条经验 获得超4个赞

看来您混淆了“是一种”和“包含”的概念。写作class Aquarium(Fish)表明这Aquarium是一种Fish,但事实并非如此。AnAquarium包含鱼。因此,Aquarium不应该源自Fish。


我认为这更像是你的意图:


class Fish:

    def __init__(self, name):

        self.name = name


    def swim(self):

        print(self.name, "is swimming!")



class Aquarium:  # An aquarium is not a kind of fish, rather it contains fish

    def __init__(self, **kwargs):

        self.fishes = []  # list of all fishes in the aquarium


        fishes = kwargs["fishes"]

        for fish_name in fishes:

            new_fish = Fish(fish_name)

            self.fishes.append(new_fish)  # add to your list


    def how_many(self):

        print("In aquarium there are " + str(len(self.fishes)) + " fishes")


    def all_swimming(self):

        print("The list of all fishes in the aquarium:")

        for fish in self.fishes:

            print("  " + fish.name)



a = Aquarium(fishes=["Nemo", "Dory"])

print(a.how_many())

a.all_swimming()


查看完整回答
反对 回复 2023-08-22
?
明月笑刀无情

TA贡献1828条经验 获得超4个赞

对的,这是可能的。但我认为这是一个更好的方法。


class Fish:

  def __init__(self, name:str):

    self.name = name

  def swim(self):

    print(self.name,"is swimming!")

    

    

class Aquarium():

  def __init__(self, fishes:Fish):

    self.fishes = []

    for fish in fishes:

      self.fishes.append(fish)

  

  def how_many(self):

    print("In acquarium there are",len(self.fishes),"fishes")

  

  def all_swimming(self):

      for fish in self.fishes:

          fish.swim()

以下是您可以更正的建议列表:

  1. 水族馆不是鱼。不要继承它!如果您需要 Fish 类的某个方面,则拆分该类并进行组合。

  2. 字典用于存储键和值。但鱼已经知道这个关键了。那么为什么不使用列表呢?你需要字典吗?如果不使用列表,则更容易使用(这只是我个人的意见)。

  3. 你使用了**kwargs。虽然这是可用的,但没有人能清楚地理解您到底想要这些参数是什么。通常最好使用一组明确定义的参数。

  4. 使用打字。至少对于参数而言。这对于更好地理解您的代码确实很有帮助。如果您这样做,您的 IDE 也可能会变得更有帮助。


查看完整回答
反对 回复 2023-08-22
  • 2 回答
  • 0 关注
  • 1626 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信