【问题标题】:How to list all staticmethods of a python class如何列出python类的所有静态方法
【发布时间】:2020-05-11 07:08:06
【问题描述】:

我有一个类似于以下的课程:

from joblib import Memory
import time


def find_static_methods(cls):
    # to be implemented
    pass


class A:

    def __init__(self, cache_path: str):
        self._memory = Memory(cache_path, verbose=0)
        self._methods = {}
        for name, method in find_static_methods(A):
            self._methods[name] = self._memory.cache(method)

    def __getattribute__(self, item):
        if item in self._methods:
            return self._methods[item]
        return super(A, self).__getattribute__(item)

    @staticmethod
    def method1(a: int, b: int):
        time.sleep(3)
        return a + b

我正在尝试使用 joblib.Memory 来记忆 method1。但我事先不知道cache_path。请帮助我在这里实现find_static_methods

【问题讨论】:

  • 你关心潜在的继承方法吗?
  • 无论如何,如果你不关心继承的方法,所有的静态方法都会类似于[attr for attr in vars(A).values() if isinstance(attr, staticmethod)]。如果这样做,则必须按方法解析顺序检查所有类的属性。
  • 谢谢让我试试这个!
  • 我也不确定Memory.cache 是否可以与staticmethod 对象一起使用,您可能必须使用底层函数,可在attr.__func__ 获得
  • 我正要问同样的问题,因为我从 joblib 收到一个错误,说 staticmethod 对象不可调用。

标签: python python-3.x memoization joblib


【解决方案1】:

这是另一种方式:

A_attrs = A.__dict__
for k, v in A_attrs.items():
    if isinstance(v, staticmethod):
        print(k)

【讨论】:

  • 不确定这是否有效:我在QtCore.QObject (PyQt5) 上尝试过,它说它没有staticmethods,但事实并非如此。 PyQt5 包可能会做一些奇怪的事情。
猜你喜欢
  • 2019-08-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-27
  • 1970-01-01
  • 1970-01-01
  • 2012-04-19
  • 2011-01-17
相关资源
最近更新 更多