【问题标题】:referencing static methods from class variable从类变量中引用静态方法
【发布时间】:2011-01-12 17:52:31
【问题描述】:

我知道有这样的情况是有道理的,但不知何故我有它:

class foo
  #static method
  @staticmethod
  def test():
    pass

  # class variable
  c = {'name' : <i want to reference test method here.>}

怎么走?

仅作记录:

我认为这应该被视为 python 最糟糕的做法。如果有的话,使用静态方法并不是真正的 pythoish 方式......

【问题讨论】:

  • 如果可能,您应该考虑使用新式类。
  • 另外,请注意staticmethod 通常不应使用。 Python 为这个应用程序提供了正常的功能。
  • 这仍然不是语法有效的python

标签: python static-methods class-variables


【解决方案1】:
class Foo:
    # static method
    @staticmethod
    def test():
        pass

    # class variable
    c = {'name' : test }

【讨论】:

    【解决方案2】:

    问题是python中的静态方法是描述符对象。所以在下面的代码中:

    class Foo:
        # static method
        @staticmethod
        def test():
            pass
    
        # class variable
        c = {'name' : test }
    

    Foo.c['name'] 是描述符对象,因此不可调用。您必须在此处键入 Foo.c['name'].__get__(None, Foo)() 才能正确调用 test()。如果您不熟悉 python 中的描述符,请查看the glossary,网上有很多文档。另外,请查看this thread,它似乎与您的用例很接近。

    为简单起见,您可以在类定义之外创建 c 类属性:

    class Foo(object):
      @staticmethod
      def test():
        pass
    
    Foo.c = {'name': Foo.test}
    

    或者,如果您愿意,可以深入了解__metaclass__ 的文档。

    【讨论】:

      猜你喜欢
      • 2020-04-15
      • 1970-01-01
      • 2011-09-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-24
      • 2015-02-18
      • 2011-01-24
      • 1970-01-01
      相关资源
      最近更新 更多