referencing static methods from class variable

强颜欢笑 提交于 2020-01-24 15:02:13

问题


I know it's wired to have such a case but somehow I have it:

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

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

What's the way to it?

Just for the record:

I believe this should be considered as python worst practices. Using static methods is not really pythoish way if ever...


回答1:


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

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



回答2:


The problem is static methods in python are descriptor objects. So in the following code:

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

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

Foo.c['name'] is the descriptor object, thus is not callable. You would have to type Foo.c['name'].__get__(None, Foo)() to correctly call test() here. If you're unfamiliar with descriptors in python, have a look at the glossary, and there's plenty of docs on the web. Also, have a look at this thread, which seems to be close to your use-case.

To keep things simple, you could probably create that c class attribute just outside of the class definition:

class Foo(object):
  @staticmethod
  def test():
    pass

Foo.c = {'name': Foo.test}

or, if you feel like it, dive in the documentation of __metaclass__.



来源:https://stackoverflow.com/questions/2194185/referencing-static-methods-from-class-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!