Python: 子类 AttributeError
Python: Subclass AttributeError
Python 3.5.2
尝试访问父字段时,我的子类遇到了一些有趣的问题。一共有三个类.(Command->Newarticle->Editarticle)。代码大概是这样,我删掉了额外的方法,尽量减少代码量):
class Command(object):
__metaclass__=abc.ABCMeta ;
def __init__(self):
# set default command name
self.__name="I hate planes" ;
self.__has_ended=False ;
class Newarticle(Command):
def __init__(self, modules):
# parent init
Command.__init__(self) ;
self.__output=modules[MAIN_OUTPUT] ;
self.__input=modules[MAIN_INPUT] ;
class Editarticle(Newarticle):
def __init__(self, modules):
Newarticle.__init__(self, modules) ;
#super().__init__(modules) ;
print(dir(self)) ;
# ERROR HAPPENS HERE !
self.__output.use_random_function() ;
我确定模块中有 MAIN_OUTPUT,因为 Newarticle 完美运行。
错误文本:AttributeError: 'Editarticle' object has no attribute '_Editarticle__output'
'dir' 的打印输出是:['_Command__has_ended', '_Command__name', '_Editarticle__acc_data', '_Editarticle__art_id', ' _Newarticle__art_images', '_Newarticle__art_name', '_Newarticle__art_text', '_Newarticle__db_mod', '_Newarticle__input', '_Newarticle__output ', '_Newarticle__run_subcmds', '_Newarticle__tag_reader',...] 等等
所以问题很明显,Python 在方法之前添加了 Class 名称,甚至没有尝试在父级中查找。那么我该如何解决呢?看不出哪里出了问题,感觉自己瞎了。
P.S。我尝试调用 'super()' 而不是 'Newarticle.init(self, modules)',结果完全相同。
P.S.P.S。我试图从第一个父级('Command')中删除元类 ABC,同样的错误。
问题是您使用的是双下划线前缀,这会调用名称重整。不要那样做。这些很少有用。
只需为您的属性使用普通名称;
def __init__(self):
# set default command name
self.name = "I hate planes"
self.has_ended = False
(另外,请删除那些分号。它们在 Python 中没有使用。)
Python 3.5.2 尝试访问父字段时,我的子类遇到了一些有趣的问题。一共有三个类.(Command->Newarticle->Editarticle)。代码大概是这样,我删掉了额外的方法,尽量减少代码量):
class Command(object):
__metaclass__=abc.ABCMeta ;
def __init__(self):
# set default command name
self.__name="I hate planes" ;
self.__has_ended=False ;
class Newarticle(Command):
def __init__(self, modules):
# parent init
Command.__init__(self) ;
self.__output=modules[MAIN_OUTPUT] ;
self.__input=modules[MAIN_INPUT] ;
class Editarticle(Newarticle):
def __init__(self, modules):
Newarticle.__init__(self, modules) ;
#super().__init__(modules) ;
print(dir(self)) ;
# ERROR HAPPENS HERE !
self.__output.use_random_function() ;
我确定模块中有 MAIN_OUTPUT,因为 Newarticle 完美运行。 错误文本:AttributeError: 'Editarticle' object has no attribute '_Editarticle__output'
'dir' 的打印输出是:['_Command__has_ended', '_Command__name', '_Editarticle__acc_data', '_Editarticle__art_id', ' _Newarticle__art_images', '_Newarticle__art_name', '_Newarticle__art_text', '_Newarticle__db_mod', '_Newarticle__input', '_Newarticle__output ', '_Newarticle__run_subcmds', '_Newarticle__tag_reader',...] 等等
所以问题很明显,Python 在方法之前添加了 Class 名称,甚至没有尝试在父级中查找。那么我该如何解决呢?看不出哪里出了问题,感觉自己瞎了。
P.S。我尝试调用 'super()' 而不是 'Newarticle.init(self, modules)',结果完全相同。 P.S.P.S。我试图从第一个父级('Command')中删除元类 ABC,同样的错误。
问题是您使用的是双下划线前缀,这会调用名称重整。不要那样做。这些很少有用。
只需为您的属性使用普通名称;
def __init__(self):
# set default command name
self.name = "I hate planes"
self.has_ended = False
(另外,请删除那些分号。它们在 Python 中没有使用。)