【问题标题】:Python: nested class with static method failsPython:具有静态方法的嵌套类失败
【发布时间】:2013-04-25 08:40:21
【问题描述】:

以下代码有什么错误

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

【问题讨论】:

  • 为什么你认为你想要一个嵌套类?在 Python 中使用它的理由几乎为零。
  • " 如果您更改超类的名称(即 A),那么您将必须将其内部的所有用途更新为 A" - 这不是 超类意味着

标签: python class python-2.7 super


【解决方案1】:
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) 的详细信息,请参阅this

【讨论】:

  • 因此解决方案是:class A: def A_M(self): pass class B: @staticmethod def C(): A().A_M()
【解决方案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()

【讨论】:

  • 不起作用:...错误:def C(): super(A.B).A_M() TypeError: must be type, not classobj
  • @Developer:好的,现在再次阅读我的帖子:“另外,在 python 2.7 中,您需要使用 (object)”super 仅适用于新式类
  • 还是不行:...err: super(A.B).A_M() AttributeError: 'super' object has no attribute 'A_M'
  • @Developer:继续阅读 - super(A.B) 本质上是 object 这里”。而object.A_M() 不存在。 “你的意思是让 B 从 A 继承?还是你只是在寻找 A.A_M()?”
  • 即使继承了,也觉得不行,因为是静态的
【解决方案3】:

后来者,将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()

不确定这是您需要的,但问题仍未解决,所以我猜了。

【讨论】:

  • a.B().C() 不正确。 a.B.C() 是正确的(因为 C 在 B 中是静态的)。我投票赞成你的答案,顺便说一句。 gatto 的回答是一样的,但有点冗长。
猜你喜欢
  • 1970-01-01
  • 2016-01-05
  • 2012-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多