类中的动态函数创建

时间:2017-01-02 14:47:08

标签: python

如何在python中的类中动态创建函数,以便我可以这样做;

client = Client()
client.dynamic_function()
client.another_dynamic_function(params=123)

dynamic_function还需要接受我在调用时可以使用的选项。

1 个答案:

答案 0 :(得分:0)

这将使你能够做到这一点

class Client(object):

    @classmethod
    def _register(cls, name, **create_kwargs):
        def func(**kwargs):
          # Call your dynamic things in here...
          return kwargs

        def call(self, **kwargs):
            print('calling dynamic function {name}, created with ({create_kwargs})) results being: {result}'.format(name=name, create_kwargs=create_kwargs, result=func(**kwargs)))

        call.__name__ = name
        setattr(cls, name, call)

Client._register('dynamic1')
Client._register('dynamic2', option=123)


if __name__ == '__main__':
  client = Client()
  client.dynamic1()
  client.dynamic1(something=111)
  client.dynamic2()
  client.dynamic2(something=222)
  print(dir(client))

制作输出:

calling dynamic function dynamic1, created with ({})) results being: {}
calling dynamic function dynamic1, created with ({})) results being: {'something': 111}
calling dynamic function dynamic2, created with ({'option': 123})) results being: {}
calling dynamic function dynamic2, created with ({'option': 123})) results being: {'something': 222}
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_register', 'dynamic1', 'dynamic2']

真实世界的实施(他们不再使用)位于here。基于commitlog,原因是This allows us to add docstrings and stricter mypy annotations.

可能有更多的pythonic方式来做到这一点。但这也很好:)