gpt4 book ai didi

python - 将元类添加到库类

转载 作者:太空狗 更新时间:2023-10-30 02:58:15 24 4
gpt4 key购买 nike

在我使用的 Python 库中,我想包装库中某个类的公共(public)方法。我正在尝试使用元类来这样做。

from functools import wraps
from types import FunctionType
from six import with_metaclass

def wrapper(func):
@wraps(func)
def wrapped(*args, **kwargs):
print("wrapped %s" % func)
return func(*args, **kwargs)
return wrapped

class MetaClass(type):
def __new__(mcs, classname, bases, class_dict):
library_class_dict = bases[0].__dict__

print(library_class_dict)

for attributeName, attribute in library_class_dict.items():
if type(attribute) == FunctionType and \
not attributeName.startswith('_'):
print("%s %s" % (attributeName, attribute))
attribute = wrapper(attribute)

library_class_dict[attributeName] = attribute

print(library_class_dict)

return type.__new__(mcs, classname, bases, class_dict)

# this is the class from the library that I cannot edit
class LibraryClass(object):
def library_method(self):
print("library method")

class Session(with_metaclass(MetaClass, LibraryClass)):

def __init__(self, profile, **kwargs):
super(Session, self).__init__(**kwargs)
self.profile = profile

当你将它放入 Python 文件并运行它时,你会得到错误

TypeError: Error when calling the metaclass bases
'dictproxy' object does not support item assignment

我知道尝试直接分配给 __dict__ 是个坏主意。那不是我想做的。我更愿意将 MetaClass 添加到 LibraryClass,但我不确定如何添加。

我已经解决了有关 Python MetaClass 编程的其他 StackOverflow 问题,但还没有遇到任何试图将 MetaClass 添加到无法获取源代码的库类的问题。

最佳答案

您不能分配给 dictproxy。使用 setattr() 设置类的属性:

setattr(bases[0], attributeName, attribute)

但是,您不需要元类来执行此操作,这在这里完全是多余的。您可以在该基类上 执行此操作,并且执行一次:

for attributeName, attribute in vars(LibraryClass).items():
if isinstance(attribute, FunctionType) and not attributeName.startswith('_'):
setattr(LibraryClass, attributeName, wrapper(attribute))

这只会执行一次,而不是每次您创建 LibraryClass 的子类时执行。

关于python - 将元类添加到库类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34666489/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com