类的构造函数抛出属性错误的Python
问题描述:
这里是我的程序结构:类的构造函数抛出属性错误的Python
class parent(object):
def __init__(self): pass
def __post_init_stuff(self):
#post initialization stuff
class child(parent):
def __init__(self):
#dostuff
self.__post_init_stuff()
def otherfunc(classname, args):
classname(args)
otherfunc(child)
说我遇到的问题是,当otherstuff(child)
执行,我得到这个错误:
AttributeError: 'child' object has no attribute '_child__post_init_stuff'
任何建议?
答
Python中以__
开头的名称与C++中的protected
相似。您可以仅使用一个下划线命名,或者以self._parent__post_init_func
的名称访问它,因为这是它在范围内的错位名称。我建议第一件事,因为这是丑陋的,哈克。
您还没有发布任何有关'otherstuff'的代码 – kindall 2014-10-07 22:25:42
由于[Name mangling](https://docs.python.org/2/tutorial/classes.html#private-variables-and-class - 本地引用)。 – 2014-10-07 22:25:44
另外我会补充说,__post_init_stuff是一个非常糟糕的主意。 __init__已经是在init中发生的事情的通用函数。如果您需要在孩子中展开,那么您应该调用partens __init__,然后继续使用特定于孩子的说明。 – 2014-10-07 22:26:49