当我尝试设置从str继承的类的参数的值时,会引发错误.只有当我尝试使用myClass(arg =’test’)访问参数时才会发生错误.错误是:
TypeError: 'arg' is an invalid keyword argument for this function
问题显示在此示例中:
class A(str):
def __init__(self, arg):
pass
A("test") # Works well
A(arg = "test") # Fails
只有最后一行才会引发错误.前一行效果很好.
从int或float继承的类的问题是相同的.
更新(解决方案):
我找到了这些链接的解决方案:
解决方案是:
class A(str):
def __new__(cls, *args, **kwargs):
return str.__new__(cls)
def __init__(self, arg01):
print(arg01)
A(arg01= "test")
我不确切知道为什么会有效,我会对此进行调查.如果有人有明确的解释,我很感兴趣,我提前感谢他.
更新(我的解释):
我不确定我会说什么,但这就是我所理解的.
想象一下没有任何遗产的班级’myClass’.
当我这样做myInstance = myClass()时,会发生以下情况:
执行myClass .__ new__方法.此方法将创建对象myInstance. __new__是真正的构造函数(__init__不是构造函数!).在伪代码中,__ new__看起来像这样:
def __new__ (cls, *args, **kwargs):
myInstance = # Do some stuff to create myInstance, an object of the type passed as argument (cls).
# Add the method __init__ to myInstance.
# Call __init__ and pass to it the list 'args' and the dictionary 'kwargs' (both come from arguments of __new__). Pass to it also the object itself (self) :
obj.__init__(self, args, kwargs) :
# Do some stuff.
当我们使用不可变类型(str,int,float,tuple)时,情况会有所不同.在之前的伪代码中,我写了def __new __(cls,* args,** kwargs).对于不可变类型,方法__new__的伪代码更像是这个def __new __(cls,anUniqueValue).我并不真正理解为什么immutableTypes .__ new__的行为与其他行为不同,但事实并非如此.你可以在这个例子中看到它:
class foo():
def __init__(self):
pass
foo.__new__(foo, arg = 1)
# That works because the method __new__ look like this : def __new__(*args, **kargs).
str.__new__(str, arg = 1)
# That fails because we are trying to pass the attribute 'arg' to a method which look like this : def __new__(anUniqueValue).
从那里,我们可以理解为什么之前提出的解决方案有效.我们所做的是编辑一个不可变类型的方法__new__,就像一个可变类型一样工作.
def __new__(cls, *args, **kwargs):
return str.__new__(cls)
这两行将def __new__(cls,anUniqueValue)转换为def __new__(cls,* args,** kwargs)