Programmatically turn module/set of functions into a Python class

前端 未结 4 1056
时光说笑
时光说笑 2021-01-21 22:28

Suppose I have a file with a bunch methods as bunch_methods.py:

def one(x):
  return int(x)

def two(y)
  return str(y)

Is there a way to take th

4条回答
  •  日久生厌
    2021-01-21 23:09

    No idea why you want to do this, but a simple approach could be:

    def to_class(module):
        class TheClass(object): pass
        for attr in dir(module):
            val = getattr(module, attr)
            if callable(val):
                setattr(TheClass, attr, staticmethod(val))
        return TheClass
    

    Usage:

    >>> import math
    >>> Math = to_class(math)
    >>> m = Math()
    >>> m.sin(5)
    -0.9589242746631385
    >>> math.sin(5)
    -0.9589242746631385
    >>> Math.sin(5)
    -0.9589242746631385
    

    If the module has also some variables, you could enhance it to add non-callable objects to the class too:

    def to_class(module):
        class TheClass(object): pass
        for attr in dir(module):
            val = getattr(module, attr)
            if callable(val):
                setattr(TheClass, attr, staticmethod(val))
            else:
                setattr(TheClass, attr, val)
        return TheClass
    

    However doing more than this becomes really hard and ugly and you must have a really good reason for doing this, otherwise it's wasted effort.

提交回复
热议问题