以编程方式为类生成方法
我有大约 20 个方法可以重定向到采用原始方法的包装方法,以及其余参数:
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...
如何以编程方式添加更多这些方法?这就是我在一切开始看起来错误之前所得到的信息:
for method in 'recv', 'recvfrom', 'recvfrom_into', 'recv_into', ...:
setattr(my_socket, method, ???)
我可以通过在类定义中分配来做到这一点,还是其他感觉更自然的方法吗?
class my_socket(parent):
def makes_recv_methods(name):
# wraps call to name
def recv_meh = makes_recv_methods('recv_meh')
如果可能的话,我更愿意使用 __get__ 和朋友,而不是来自 types
的魔术函数。
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')
I'd prefer to use __get__
and friends when possible over magic functions from types
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我会通过在定义类后运行一些代码从列表中生成方法来实现这一点 - 您可以将其放入装饰器中。
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.
wilberforce 提案有效,但有一种仅使用 OOP 的更简单的方法:
wilberforce proposal works, but there is a simpler way using OOP only:
我想扩展已接受的答案。我希望可能有一个非常长的装饰器方法列表应用于一个非常长的方法列表。
这是包装原始类的类
I'd like to expand on the accepted answer. I wanted to potentially have a very long list of decorator methods applied to a very long list of methods.
And here is the class that wraps the original
您可以使用cog。
这样做的额外优点是易于更新,不会触及结束注释之外的代码,并且如果需要,您可以调整生成的代码。
我已经成功地使用 cog 在另一个项目上生成样板文件,并与非生成的代码混合在一起。它首先将指令输入文件读入字典。然后,对于样板文件的每个部分,它都使用字典的那一部分来知道要写什么。
我在一个位置编辑指令文件,而不是在样板文件中的二十个不同位置。
You could use cog.
This has the added advantages of easily being updated, not touching your code outside of the end comment, and you can twiddle the generated code if necessary.
I've successfully used cog for generating boilerplate on another project, mixed in with the non generated code. It started out reading an input file of instructions into a dictionary. Then for each section of boilerplate it used that piece of the dictionary to know what to write.
I edit the instruction file in one spot, instead of twenty different places in the boilerplate.