如何使嵌套类继承?

-1 投票
1 回答
802 浏览
提问于 2025-04-18 09:06

我正在尝试在一个类里面初始化一个继承的类,但这不管用,我不知道该怎么解决。

我在这里看到,继承通常是这样工作的:

class Foo(object):
    def __init__(self, text):
        print text

class Bar(Foo):
    def __init__(self, text):
        super(Bar, self).__init__(text)

这样是可以的,但是如果我把Bar类放到另一个类里面,代码就不再有效了。

class Whatever(object):
    class Bar(Foo):
        def __init__(self, text):
            super(Bar, self).__init__(text)

    def __init__(self, text):
        test = self.Bar(text)

Python在命名空间上搞混了:

super(Bar, self).__init__(text)
NameError: global name 'Bar' is not defined

该怎么办呢?谢谢!

1 个回答

1

问题解决了。

你需要用 Whatever.Bar 来引用 Bar,所以看起来是这样的:

class Whatever(object):
    class Bar(Foo):
        def __init__(self, text):
            super(Whatever.Bar, self).__init__(text)

    def __init__(self, text):
        test = self.Bar(text)

撰写回答