2014-10-07 57 views
-1

这里是我的程序结构:类的构造函数抛出属性错误的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'

任何建议?

+0

您还没有发布任何有关'otherstuff'的代码 – kindall 2014-10-07 22:25:42

+3

由于[Name mangling](https://docs.python.org/2/tutorial/classes.html#private-variables-and-class - 本地引用)。 – 2014-10-07 22:25:44

+2

另外我会补充说,__post_init_stuff是一个非常糟糕的主意。 __init__已经是在init中发生的事情的通用函数。如果您需要在孩子中展开,那么您应该调用partens __init__,然后继续使用特定于孩子的说明。 – 2014-10-07 22:26:49

回答

0

Python中以__开头的名称与C++中的protected相似。您可以仅使用一个下划线命名,或者以self._parent__post_init_func的名称访问它,因为这是它在范围内的错位名称。我建议第一件事,因为这是丑陋的,哈克。