gpt4 book ai didi

python - 类型错误 : type() takes 1 or 3 arguments

转载 作者:行者123 更新时间:2023-12-04 18:37:22 25 4
gpt4 key购买 nike

我有一个 TypeClass 来制作类:

class MyMetaClass(type):

def __new__(cls, *args, **kwargs):
print('call __new__ from MyMetaClass.')
return type(cls.__name__, *args, **kwargs)

但是当使用它时:
Foo= MyMetaClass('Foo', (), {'name':'pd'})

引发错误:
TypeError: type() takes 1 or 3 arguments

如果改变它:
class MyMetaClass(type):
def __new__(cls, *args, **kwargs):
print('call __new__ from MyMetaClass.')
return type(cls.__name__, (), {})

它会正常工作的!
哪里有问题?

最佳答案

__new__方法在 args 中传递了 3 个位置参数;类名、基类和类体。 cls参数绑定(bind)到元类,所以 MyMetaClass这里。

您正在为该序列添加另一个名称;删除名称,或从 args 中删除第一个参数:

class MyMetaClass(type):
def __new__(cls, *args, **kwargs):
print('call __new__ from MyMetaClass.')
return type(*args, **kwargs)

或者
class MyMetaClass(type):
def __new__(cls, *args, **kwargs):
print('call __new__ from MyMetaClass.')
return type(cls.__name__, *args[1:], **kwargs)
cls然而,参数是元类对象,因此除非您希望将所有类都称为 MyMetaClass我会坚持第一个选项。

Customizing class creation section Python数据模型:

These steps will have to be performed in the metaclass’s __new__() method – type.__new__() can then be called from this method to create a class with different properties. This example adds a new element to the class dictionary before creating the class:

class metacls(type):
def __new__(mcs, name, bases, dict):
dict['foo'] = 'metacls was here'
return type.__new__(mcs, name, bases, dict)


object.__new__ documentation :

__new__() is a static method (special-cased so you need not declare it as such) that takes the class of which an instance was requested as its first argument. The remaining arguments are those passed to the object constructor expression (the call to the class).



其中请求实例的类是您的元类(产生一个类对象)。

演示:
>>> class MyMetaClass(type):
... def __new__(cls, *args, **kwargs):
... print('call __new__ from MyMetaClass.')
... return type(*args, **kwargs)
...
>>> class Foo(object):
... __metaclass__ = MyMetaClass
...
call __new__ from MyMetaClass.
>>> Foo
<class '__main__.Foo'>
>>> class MyMetaClass(type):
... def __new__(cls, *args, **kwargs):
... print('call __new__ from MyMetaClass.')
... return type(cls.__name__, *args[1:], **kwargs)
...
>>> class Foo(object):
... __metaclass__ = MyMetaClass
...
call __new__ from MyMetaClass.
>>> Foo
<class '__main__.MyMetaClass'>
>>> # Note the ^^^^^^^^^^^^ class.__name__ attribute here
...

关于python - 类型错误 : type() takes 1 or 3 arguments,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32439083/

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