代码之家  ›  专栏  ›  技术社区  ›  khelll

从类变量引用静态方法

  •  2
  • khelll  · 技术社区  · 15 年前

    我知道有这样一个案子是有关联的,但不知何故,我有:

    class foo
      #static method
      @staticmethod
      def test():
        pass
    
      # class variable
      c = {'name' : <i want to reference test method here.>}
    

    怎么走?

    只是为了记录:

    我认为这应该被视为Python最糟糕的实践。使用静态方法不是真正的蟒蛇式的方式,如果有的话…

    2 回复  |  直到 15 年前
        1
  •  5
  •   Will McCutchen    15 年前
    class Foo:
        # static method
        @staticmethod
        def test():
            pass
    
        # class variable
        c = {'name' : test }
    
        2
  •  3
  •   SilentGhost    15 年前

    问题是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__ .

    推荐文章