Python:没有在子类init中指定变量,调用方法有问题

2024-09-28 15:25:04 发布

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

我有一个超类,它有很多参数。我想创建一个子类,它共享所有这些参数并添加额外的一个或两个参数。为了避免双重编码,我使用了Avoid specifying all arguments in a subclass中指定的方法:

class Container(Item):

  def __init__(self,**kwargs):
    try: self.is_locked=kwargs.pop('is_locked')
    except KeyError: pass
    super(Container, self).__init__(**kwargs)

  def open(self):
    print "aw ys"

但是,当我尝试调用容器类的对象时:

> some_container.open()
AttributeError: 'Item' object has no attribute 'open'

似乎some容器不是container(),而是一个带有单个变量的Item()。\u。我做错什么了?你知道吗

编辑:我的项目定义:

class Item(object:
def __init__(self,istemplate,id,short,long,type,flags,value,damagerange,damagereductionrange,weight): 
    if istemplate==False:
        self.__class__.instances.append(self)
    self.istemplate=istemplate
(... many variables like that...)
    self.id=id
    self.randomizestuff() 
    if istemplate==True:
        self.__class__.templates.append(copy.deepcopy(self))

Tags: selfid参数initiscontainerdefsome
1条回答
网友
1楼 · 发布于 2024-09-28 15:25:04

好吧,经过一番研究,我发现事实上我并不是在引用某个容器_容器.打开(),而是由从同一模板创建项实例的函数创建的动态项。该函数将新实例定义为Item(...),而不是Container(...),因为它是在引入任何子类之前创建的。你知道吗

some_container=Container(...)
some_container.open()

以上从一开始就行,因此paidhima无法复制我的错误。你知道吗

相关问题 更多 >