Programmatically turn module/set of functions into a Python class

前端 未结 4 1069
时光说笑
时光说笑 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:11

    You can also solve this problem using the type meta-class. The format for using type to generate a class is as follows:

    type(name of the class, 
       tuple of the parent class (for inheritance, can be empty), 
       dictionary containing attributes names and values)
    

    First, we need to rework your functions to take a class as the first attribute.

    def one(cls, x):
        return int(x)
    
    def two(cls, y):
        return str(y)
    

    Save this as bunch_method.py, and now we can construct our class as follows.

    >>> import bunch_methods as bm
    >>> Bunch_Class = type('Bunch_Class', (), bm.__dict__)
    >>> bunch_object = Bunch_Class()
    >>> bunch_object.__class__
    
    >>> bunch_object.one(1)
    1
    >>> bunch_object.two(1)
    '1'
    

    See the following post for a excellent (and long) guide on meta-classes. What is a metaclass in Python?

提交回复
热议问题