Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/323.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在不初始化Python中的新类的情况下编辑继承类的属性?_Python_Class_Oop_Inheritance_Attributes - Fatal编程技术网

如何在不初始化Python中的新类的情况下编辑继承类的属性?

如何在不初始化Python中的新类的情况下编辑继承类的属性?,python,class,oop,inheritance,attributes,Python,Class,Oop,Inheritance,Attributes,我的问题很好地说明了这个问题,所以我将直接讨论代码 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 我要做的是继承

我的问题很好地说明了这个问题,所以我将直接讨论代码

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

我要做的是继承大多数类属性,只编辑这两个属性(伤害、生命值),有什么方法可以做到这一点而不必创建一个完整的其他类吗?

好的,这里有两件事情不太正确。首先,
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
这会让你达到你想要的工作状态

编辑

如果您真的不想为每种类型的boxer使用子类,另一种方法是在构造函数中使用默认值,这些值可以被重写。因此:

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


您是否在问是否可以编写一个继承自另一个类的类而不编写类?请不要要求读者不要向您介绍其他问题。如果有人认为这是重复的,他们可能发现了一些你没有发现的东西。@roganjosh不会,但不清楚问题中是否只有一个
Prince
或多个-,从上下文来看,我认为OP不想为每个实例生成一个全新的类,但我可能错了。如果需要多个不同的王子,那么是的,它应该有自己的类。只有一个,用户会选择一个类并命名他们的角色,但是我觉得为每个可玩类创建类最容易添加其他属性
Boxer("Alan") # Ordinary boxer
Boxer("Prince", damage=40, health=80) # Prince is special