【问题标题】:Class Inheritance and Creation in Python [closed]Python中的类继承和创建[关闭]
【发布时间】:2021-11-15 21:49:29
【问题描述】:

当您在 Python 中创建 2 个类时,第二个类是否总是必须是子类或子类?是否可以有两个以对象为参数的类?谢谢!

class Bird(object):
  def __init__(self, name):
    self.name = name
    print("A %s has feathers" % self.name)
 
class Seagull(object):
  def __init__(self):
    print("Seagulls can fly")
    super().__init__('Seagull')
 
seagull = Seagull()

这段代码有什么问题?它说 Seagull 是一个继承,所以它的(对象)应该是 Bird……但是为什么呢?

【问题讨论】:

  • 问题需要更多细节。很难理解被问到什么
  • 所有类都继承自object,所以在这个意义上它们都是子类。但是你可以有尽可能多的课程。他们不必互相继承。我不确定“将对象作为参数”是什么意思。由于所有对象都追溯到object,因此任何类型的所有参数都以object为根。
  • class Bird(object): def __init__(self, name): self.name = name print("A %s has feathers" % self.name) class Seagull(object): def __init__( self): print("Seagulls can fly") super().__init__('Seagull') seagull = Seagull() 这段代码有什么问题?它说 Seagull 是一个继承,所以它的(对象)应该是 Bird……但是为什么呢?
  • 首先在python3中不需要继承object,它是自动完成的,所以只需将类写成class Bird:class Seagull:,其次,super()调用父对象,在本例中为 object 并传递给定的参数(在本例中为字符串),但 object 不接受任何参数。您想要实现的目标有点令人困惑
  • “它说 Seagull 是一个继承” -- 那是什么意思?如果我运行代码,我会在super().__init__('Seagull') 得到TypeError: object.__init__() takes exactly one argument (the instance to initialize)。您是否在某种代码测试站点中运行它?请提供minimal reproducible example,包括预期输出和实际输出。顺便说一句,欢迎来到 Stack Overflow!请收下tour 并阅读How to Ask

标签: python class oop


【解决方案1】:

你有子类还是独立类取决于你正在实现的逻辑。

对于鸟和海鸥,您可能需要一个子类,因为海鸥是一种鸟:

class Bird(object):
    ...

class Seagull(Bird):
    ...

在其他情况下,您可能需要单独的类,彼此不相关:

class Bird(object):
    ...

class Locomotive(object):
    ...

顺便说一句,在 Python 3 中,(object) 部分在字面上是 object 时是不需要的,所以我们通常会这样写:

class Bird:
    ...

class Seagull(Bird):
    ...

class Locomotive:
    ...

【讨论】:

  • object继承在python 3中是多余的,只需使用class Bird:
  • 在答案中更新
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-08-28
  • 1970-01-01
相关资源
最近更新 更多