0

次のコードの 何が問題になっていますか?

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

エラー (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

編集
解決策は次のように簡単でした:

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

このソリューションには問題があることに注意してください。スーパークラスの名前を変更した場合 (つまりA)、それ自体の内部のすべての使用を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 に答える