0

What is wrong with the following code?

class A:
    def A_M(self): pass
    class B:
        @staticmethod
        def C(): super(B).A_M()

error (Python 2.7.3):

>>> a = A()
>>> a.B.C()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "..x.py", line 36, in C
    def C(): super(B).A_M()
NameError: global name 'B' is not defined

Edit:
the solution was simple as this:

class A:
    def A_M(self): pass
    class B:
        @staticmethod
        def C(): A().A_M()                 #use of A() instead of supper, etc.

Important Note that there is an issue with this solution. If you change the name of super class (i.e. A) then you will have to update all uses inside itself as A :)).

4

3 回答 3

3
class A(object):
    def foo(self):
        print('foo')

    @staticmethod
    def bar():
        print('bar')

    class B(object):
        @staticmethod
        def bar(obj):
            # A.foo is not staticmethod, you can't use A.foo(),
            # you need an instance.
            # You also can't use super here to get A,
            # because B is not subclass of A.
            obj.foo()
            A.foo(obj)  # the same as obj.foo()

            # A.bar is static, you can use it without an object.
            A.bar()

class B(A):
    def foo(self):
        # Again, B.foo shouldn't be a staticmethod, because A.foo isn't.
        super(B, self).foo()

    @staticmethod
    def bar():
        # You have to use super(type, type) if you don't have an instance.
        super(B, B).bar()


a, b = A(), B()

a.B.bar(a)
b.foo()
B.bar()

有关. _ _super(B, B)

于 2013-04-25T09:46:26.070 回答
2

您需要使用完全限定的名称。此外,在 python 2.7 中,您需要使用(object),否则super(A.B)会给出TypeError: must be type, not classobj

class A(object):
    def A_M(self):
        pass

    class B(object):
        @staticmethod
        def C():
            super(A.B).A_M()

最后,super(A.B)基本上就是object这里了。你的意思是B继承自A?还是您只是在寻找A.A_M()

于 2013-04-25T08:41:27.097 回答
2

一个后来者,将 B 封装在 A 中的简单方法是:

class A:
    def A_M(self):
        return "hi"

    class B:
        @staticmethod
        def C():
            return A().A_M()

a = A()
print a.B().C()

不确定这是你需要的,但问题仍然没有解决,所以我猜到了。

于 2013-04-25T10:09:54.517 回答