python - 以编程方式将模块/函数集转换为 Python 类

标签 python class function methods module

假设我有一个包含一堆方法的文件,如 bunch_methods.py:

def one(x):
  return int(x)

def two(y)
  return str(y)

有没有办法通过导入整个模块或选择方法来获取这组方法,并将导入的方法变成一个类?

例如伪智慧

def make_class_from_module(which_module_or_listing_of_methods):
    class = turn_module_to_class(which_module_or_listing_of_methods)
    return class

所以

BunchClass = make_class_from_module(bunch_methods)

在我看来这听起来很合理,但它的可行性如何?如果我应该,我将如何开始做这样的事情,或者我有什么选择?

我为什么要这样做?现在这是一种心理和学习练习,但我的具体用途是采取方法并创造 flask-classy FlaskView classes .我想潜在地获取大量方法,并可能在 FlaskView 的不同上下文中使用和重用它们


最佳答案

这是一个简单(但很长)的单行 lambda,它可以做你想做的事(部分灵感来自 Bakuriu)。

classify = lambda module: type(module.__name__, (), {key: staticmethod(value) if callable(value) else value for key, value in ((name, getattr(module, name)) for name in dir(module))})

您可能会发现以下函数更易于阅读,并且在理解中更容易看到循环。

def classify(module):
    return type(module.__name__, (),
                {key: staticmethod(value) if callable(value) else value
                 for key, value in ((name, getattr(module, name))
                                    for name in dir(module))})

用法实际上与 Bakuriu 的回答 相同,正如您在与口译员交谈时所见。

>>> import math
>>> MathClass = classify(math)
>>> MathClass.sin(5)
-0.9589242746631385
>>> instance = MathClass()
>>> instance.sin(5)
-0.9589242746631385
>>> math.sin(5)
-0.9589242746631385
>>> 

附录:

在实现将模块转换为类的一种用途后,编写了以下示例程序,展示了如何将转换后的模块用作基类。该模式可能不推荐用于普通用途,但确实展示了该概念的有趣应用。 classify 函数在下面显示的版本中也应该更易于阅读。

import math


def main():
    print(Point(1, 1) + Point.polar(45, Point.sqrt(2)))


def classify(module):
    return type(module.__name__, (), {
        key: staticmethod(value) if callable(value) else value
        for key, value in vars(module).items()
    })


class Point(classify(math)):

    def __init__(self, x, y):
        self.__x, self.__y = float(x), float(y)

    def __str__(self):
        return str((self.x, self.y))

    def __add__(self, other):
        return type(self)(self.x + other.x, self.y + other.y)

    @property
    def x(self):
        return self.__x

    @property
    def y(self):
        return self.__y

    @classmethod
    def polar(cls, direction, length):
        radians = cls.radians(direction)
        x = round(cls.sin(radians) * length, 10)
        y = round(cls.cos(radians) * length, 10)
        return cls(x, y)


if __name__ == '__main__':
    main()

关于python - 以编程方式将模块/函数集转换为 Python 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16717577/

相关文章:

python - "Fatal: too many params"从 python 调用 bash 命令时,直接在 git bash 中使用相同命令没有错误

java - 将对象变量放入扫描仪中

c - 由于比较错误,函数未返回 0

类属性初始值的 TypeScript 差异

java - 如何在java中的类中声明对象的ArrayList?

function - 获取Lua脚本中的所有函数

function - 从 Julia 中的函数中收集值

python - CMake FindPython3 无法在 Windows 上找到解释器

php - 为什么从 PHP 调用的长时间运行的 Python 脚本会失败

python - 如何统计标签的使用次数并在html中显示?