Python new方法,求详解
class Nint(int):def __new__(cls,args=0):
if isinstance(args,str):
total=0
for i in args:
total+=ord(i)
args=total
return int.__new__(cls,args)
n1=Nint()#形参args=0有默认值,为什么不传入参数还要报错
print(n1)
print('-'*8)
n2=Nint('abc')
print(n2)
因为你给args赋值的是0
而
for i in args:
数字是不能 for 循环迭代
所以就会报错
试着给args赋值这个吧~
class Nint(int):
def __new__(cls,args='我好帅呀~'):
if isinstance(args,str):
total=0
for i in args:
total+=ord(i)
args=total
return int.__new__(cls,args)
>>> a=Nint()
>>> print(a)
93777{:10_254:}
页:
[1]