Python:使用静态方法的嵌套类失败 [英] Python: nested class with static method fails

查看:124
本文介绍了Python:使用静态方法的嵌套类失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下代码有什么错误

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



< 2.7.3):

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.

重要说明:此解决方案存在问题。如果你改变超类的名字(即 A ),那么你必须更新里面的所有用法 A :))。

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 :)).

推荐答案

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)

这篇关于Python:使用静态方法的嵌套类失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆