Python: nested class with static method fails
以下代码有什么问题?
1 2 3 4 5 | class A: def A_M(self): pass class B: @staticmethod def C(): super(B).A_M() |
错误(python 2.7.3):
1 2 3 4 5 6 7 | >>> 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 |
编辑:解决方案很简单,如下所示:
1 2 3 4 5 | class A: def A_M(self): pass class B: @staticmethod def C(): A().A_M() #use of A() instead of supper, etc. |
重要提示:此解决方案存在问题。如果您更改了超级类的名称(即
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | 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() |
有关
A latecommer,简单地封装B是:
1 2 3 4 5 6 7 8 9 10 11 | class A: def A_M(self): return"hi" class B: @staticmethod def C(): return A().A_M() a = A() print a.B().C() |
不确定这是你需要的,但是这个问题仍然没有解决,所以我猜。
您需要使用完全限定的名称。另外,在python 2.7中,需要使用
1 2 3 4 5 6 7 8 | class A(object): def A_M(self): pass class B(object): @staticmethod def C(): super(A.B).A_M() |
最后,这里的