[英]How to extend protobuf objects in python
I've defined a protobuf message that I'd like to create a wrapper/proxy/boilerplate/extension/anything for so I can add custom methods.我已经定义了一个 protobuf 消息,我想为它创建一个包装器/代理/样板/扩展/任何东西,以便我可以添加自定义方法。
The docs for protobuf say that you are advised not to inherit directly from the protobuf as under the hood, it's actually a descriptor and metaclass that define most of the methods/attributes. protobuf 的文档说,建议您不要直接从 protobuf 继承,因为它实际上是定义大多数方法/属性的描述符和元类。
I was wondering how people go about "inheriting" a class as best as possible when inheritance is not a stable option, or if anyone has had any luck using protobuf codegen to extend/define a custom Message class and if that's a reasonable idea.我想知道当继承不是一个稳定的选择时,人们如何尽可能地“继承”一个类,或者是否有人有幸使用 protobuf codegen 扩展/定义自定义 Message 类,如果这是一个合理的想法。
Never worked with protobuf, and dont know if the dir
function of python will work on it.没用过protobuf,不知道python的
dir
函数能不能用。 But if it does you can do something like that:但如果是这样,你可以做这样的事情:
class A:
def app(self):
print("app")
def bla(self):
print("bla")
class wrapperA:
def __init__(self,a):
self.dict_of_functions = {x:getattr(a, x) for x in dir(A)}
def funcA(self, func_name):
return self.dict_of_functions[func_name]()
a = A()
wa = wrapperA(a)
for x in ["app", "bla"]:
wa.funcA(x)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.