【问题标题】:How to edit the attributes of an inherited class without initializing a new class in Python? [closed]如何在不初始化 Python 中的新类的情况下编辑继承类的属性? [关闭]
【发布时间】:2018-01-01 22:34:15
【问题描述】:

我的问题很好地说明了问题,所以我将直接进入代码。

class Boxer:
    def __init__(self, name):
        self.name = name
        self.health = 100
        self.damage = 20
        self.power = 30

这里是原始类或父类

class Prince(Boxer):
    self.damage = 40
    self.health = 80

我想要做的是继承大多数类属性,并且只编辑这两个(伤害,健康),有没有办法做到这一点而不必创建一个完整的其他类?

【问题讨论】:

  • 你是在问,不写类,能不能写出继承自另一个类的类?
  • 请不要让读者不要参考其他问题。如果有人认为这是重复的,他们可能发现了一些你没有发现的东西。

标签: python class oop inheritance attributes


【解决方案1】:

好吧,这里有两件事不太对劲。首先,Prince - self 的代码只能在方法内部使用,比如构造函数。 Prince 的属性实际上应该如下所示:

class Prince(Boxer):
    damage = 40
    health = 80

其次,Boxer 中的构造函数将在调用时覆盖这些默认值。因此,对于那些可覆盖的,您需要在类定义中设置属性,而不是在构造函数中:

class Boxer:
    health = 100
    damage = 20
    power = 30

    def __init__(self, name):
        self.name = name

这应该能让你在某个地方按你的意愿工作。

编辑

如果您真的不想为每种类型的拳击手使用子类,另一种方法是在构造函数中使用默认值,并且可以覆盖这些值。所以:

class Boxer:
    def __init__(self, name, health=100, damage=20, power=30):
        self.name = name
        self.health = health
        self.damage = damage
        self.power = power

然后:

Boxer("Alan") # Ordinary boxer
Boxer("Prince", damage=40, health=80) # Prince is special

【讨论】:

  • @roganjosh 不会,但不清楚问题中是否只有一个 Prince 或多个 - 从上下文来看,我认为 OP 不想为每个实例,但我可能是错的。如果需要多个不同的 Princes,那么是的,它应该有自己的类。
  • 只有一个,用户会选择一个类并命名他们的角色,但是我觉得为每个可玩的创建类是最容易添加到其他沿途属性
猜你喜欢
  • 2010-12-24
  • 1970-01-01
  • 1970-01-01
  • 2019-09-05
  • 1970-01-01
  • 2022-01-12
  • 1970-01-01
  • 1970-01-01
  • 2020-11-24
相关资源
最近更新 更多