如何跟踪传递给元类的关键字? [英] How to keep track of keywords passed to metaclass?
问题描述
我有一个接受关键字参数的元类:
I have a metaclass that accepts keyword arguments:
class M(type):
def __new__(cls, *args, **kwargs):
print(*kwargs.items())
super().__new__(cls, *args)
它按预期工作:
class A(metaclass=M, test='X'): pass
产生对象A
和打印输出
('test', 'X')
我想使用此之类的东西来复制A
:
I would like to make a copy of A
using something like this:
def copy_class(cls, name=None):
if name is None:
name = cls.__name__
return type(cls)(name, cls.__bases__, dict(cls.__dict__))
A_copy = copy_class(A, 'A_copy')
但是,关键字不存在.当type(cls)
需要附加参数,或者在不存在附加副作用时会产生不同的副作用时,这尤其是个问题.
However, the keywords are not present. This is especially a problem when type(cls)
requires additional arguments or otherwise produces different side-effects when they are not there.
我知道我可以将M
关键字存储在类对象中的某个位置,但这不是一个很好的解决方案,因为那时我的复制方法非常依赖于类.
I am aware that I can have M
stash the keywords in the class object somewhere, but this is not a very good solution because then my copy method is very class-dependent.
是否有内置的方法来检索使用Python创建类的关键字?
Is there a built-in way to retrieve the keywords a class was created with in Python?
推荐答案
Python不会为您保存关键字参数.这很容易演示:
Python will not save the keyword arguments for you. This is simple to demonstrate:
>>> class DoesntSaveKeywords(type):
... def __new__(cls, name, bases, dict, **kwargs):
... return super().__new__(cls, name, bases, dict)
...
>>> class PrintsOnDel:
... def __del__(self):
... print('__del__')
...
>>> class Foo(metaclass=DoesntSaveKeywords, keyword=PrintsOnDel()):
... pass
...
__del__
此外,我认为尝试复制这样的类的基本想法没有道理.不能保证该类的__dict__
看起来像最初传递给元类构造函数的东西,或者再次调用该元类构造函数将做任何合理的事情.
Also, I don't think the underlying idea of trying to copy a class like this makes sense. There's no guarantee that the class's __dict__
looks anything like what was originally passed to the metaclass constructor, or that calling the metaclass constructor again will do anything remotely reasonable.
这篇关于如何跟踪传递给元类的关键字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!