python元类传递__init__ params

问题描述 投票:0回答:1

我正在学习python 3中的元类编程,但是我遇到了一些问题

class UpperAttrMetaClass(type): # to uppercase all attrs
    def __new__(mcs, class_name, class_parents, class_attr):
        attrs = ((name, value) for name, value in class_attr.items() if not 
            name.startswith('__'))
        uppercase_attrs = dict((name.upper(), value) for name, value in attrs)
        return super(UpperAttrMetaClass, mcs).__new__(mcs, class_name, 
                     class_parents, uppercase_attrs)

class Base(metaclass=UpperAttrMetaClass):
    bar = 12
    def __init__(self, params):
        super(Base, self).__init__()
        self.params = params

t = Base(1)
print(t.BAR)
print(t.params)

此代码可以大写所有attrs。

我想将一个参数传递给init,但是当我运行这段代码时,我被提示犯了一个错误

TypeError: object() takes no parameters

我怎么解决这个问题?

python init metaclass
1个回答
1
投票

您正在过滤__init__方法:

attrs = ((name, value) for name, value in class_attr.items() if not 
    name.startswith('__'))

attrs是所有不以__开头的属性。然后你将那些attrs大写并将它们用于你创建的类,所以__init__从未用于新类。因为生成的Bar类没有__init__方法,所以使用了object.__init__,并且该方法不带参数:

>>> sorted(vars(Base))
['BAR', '__dict__', '__doc__', '__module__', '__weakref__']
>>> Base.__init__
<slot wrapper '__init__' of 'object' objects>

包括所有属性,不过滤,但只包含没有__的那些:

class UpperAttrMetaClass(type): # to uppercase all attrs
    def __new__(mcs, class_name, class_parents, class_attr):
        attrs = {name if name.startswith('__') else name.upper(): value for name, value in class_attr.items()}
        return super().__new__(mcs, class_name, class_parents, attrs)

我在这里使用字典理解;请注意name if name.startswith('__') else name.upper()条件表达式,当名称不以__开头时,它会生成一个大写的属性名称。

我还使用了super()的0参数形式,毕竟这是Python 3。

现在元类正常工作,Base.__init__存在:

>>> sorted(vars(Base))
['BAR', '__dict__', '__doc__', '__init__', '__module__', '__weakref__']
>>> t = Base(1)
>>> t.BAR
12
>>> t.params
1
© www.soinside.com 2019 - 2024. All rights reserved.