以编程方式生成类的方法 [英] Programmatically generate methods for a class

查看:76
本文介绍了以编程方式生成类的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我大约有20种方法可以重定向到采用原始方法的包装器方法,其余参数则为

I have about 20 methods to redirect to a wrapper method that takes the original method, and the rest of the arguments:

class my_socket(parent):

    def _in(self, method, *args, **kwargs):
        # do funky stuff

    def recv(self, *args, **kwargs):
        return self._in(super().recv, *args, **kwargs)

    def recv_into(self, *args, **kwargs):
        return self._in(super().recv_into, *args, **kwargs)

    # and so on...

如何以编程方式添加更多这些方法?据我所知,一切似乎都开始出现错误:

How can I add more of these methods programmatically? This is about as far as I get before everything starts to look wrong:

for method in 'recv', 'recvfrom', 'recvfrom_into', 'recv_into', ...:
    setattr(my_socket, method, ???)

我可以通过在类定义中进行赋值还是其他更自然的方法来做到这一点?

Can I do this by assigning within the class definition, or something else that feels more natural?

class my_socket(parent):

    def makes_recv_methods(name):
        # wraps call to name

    def recv_meh = makes_recv_methods('recv_meh')

types的魔术函数相比,我更愿意使用__get__和朋友.

I'd prefer to use __get__ and friends when possible over magic functions from types.

推荐答案

我可以通过在定义类后运行一些代码以从列表中生成方法来做到这一点-您可以将其放入装饰器中.

I'd do it by running some code to generate the methods from a list after the class is defined - you could put this into a decorator.

import functools

def wrap_method(cls, name):
    # This unbound method will be pulled from the superclass.
    wrapped = getattr(cls, name)
    @functools.wraps(wrapped)
    def wrapper(self, *args, **kwargs):
        return self._in(wrapped.__get__(self, cls), *args, **kwargs)
    return wrapper

def wrap_methods(cls):
    for name in cls.WRAP_ATTRS:
        setattr(cls, name, wrap_method(cls, name))
    return cls

@wrap_methods
class my_socket(parent_class):
    WRAP_ATTRS = ['recv', 'recvfrom'] # ... + more method names

    def _in(self, method, *args, **kwargs):
        # do funky stuff

这篇关于以编程方式生成类的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆