python int float str_python – 在继承自int或float或str的类中设置参数的值

当我尝试设置从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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值