Python 如何使用类值作为多个子类的默认值?
我相信这很简单,但我是新手 我有一套课程。我们打电话吧Python 如何使用类值作为多个子类的默认值?,python,python-3.x,Python,Python 3.x,我相信这很简单,但我是新手 我有一套课程。我们打电话吧 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, na
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:\uuuu init\uuuu()缺少1个必需的位置参数:'type'
”
本质上,我的目标是,对于ChildSubType,我只能被要求输入名称,如果我没有输入颜色或类型,那么它将默认为颜色的ChildSubType类中的值,并且它将默认为类型的子类
我不完全确定如何做到这一点
我假设它与ChildSubType中的def\uuuu init\uuuu
方法有关,但我也不完全清楚这应该做什么。在这一点上,我基本上是按照指示进行的,并且遇到了这个障碍
值得一提的是,我还尝试只使用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)
当前,中的
\uuuu init\uuuu
方法包含3个初始化变量,但在创建对象时仅传递2个。我建议使用以下默认值:
def __init__(self, name, color='None', type=None):
我认为您可以在这里使用关键字参数
\uuuu init\uuuu(…,type='default')
,这很有意义。。。但是,如果我没有在ChildSubType中定义它,我将如何从子类调用默认值?默认的type
将通过您的super
调用传递。实际上,我将避免重写内置的type