如何使用类值作为多个子类的默认值?

2024-09-30 08:25:48 发布

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

我相信这很简单,但我是新手

我有一套课程。我们打电话吧

class Parent:

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

class Mix: 
    def BMethod(self):
        return '{0} is right'

class Child(Parent, Mix):
    def __init__(self, name, color, type):
        self.type = 'AAA'
        self.color = 'None'
        super(Child,self).__init__(name,color)

    def __str__(self):
        return '{0} is a {1} {2}.'.format(self.name,self.color,self.type)

class ChildSubType(Child, Mix):
    def __init__(self, name, color, type):
        color = 'None'
        kind = super().kind
        super(ChildSubType,self).__init__(name,color,type)

    def __str__(self):
        return "{0} is not a {1} {2}".format(self.name,self.color.self.type)


childsubtype = ChildSubType(
    "Name1"
    ,"White"
)

print(childsubtype)

当我运行这段代码时,我得到一个错误,上面写着“TypeError: __init__() missing 1 required positional argument: 'type'

本质上,我的目标是,对于ChildSubType,我只能被要求输入名称,如果我没有输入颜色或类型,那么它将默认为颜色的ChildSubType类的值,并且它将默认为类型的Child类

我不完全确定如何做到这一点

我假设它与ChildSubType中的def __init__方法有关,但我也不是100%清楚它应该做什么。在这一点上,我基本上是按照指示,并已击中这个路障

值得一提的是,我还尝试过只使用Child而不使用ChildSubType来运行它,并遇到了相同的错误。我想我只是不知道如何在类中使用默认值

编辑: 好吧,我想我已经成功了。我更新了代码,按照注释中的建议给它一个默认值

以下是我所改变的:

Class Child(Parent, Mix):
    def __init__(self, name, color, **type = 'AAA'**):
        self.type = 'AAA'
        self.color = 'None'
        super(Child,self).__init__(name,color)

    def __str__(self):
        return '{0} is a {1} {2}.'.format(self.name,self.color,self.type)

class ChildSubType(Child, Mix):
    def __init__(self, name, color, **type = super(type)**):
        color = 'None'
        kind = super().kind
        super(ChildSubType,self).__init__(name,color,type)

Tags: nameselfnonechildreturninitisdef
1条回答
网友
1楼 · 发布于 2024-09-30 08:25:48

当前,中的__init__方法包含3个初始化变量,但在创建对象时只传递2个。我建议使用如下默认值:

def __init__(self, name, color='None', type=None):

相关问题 更多 >

    热门问题