|
|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
在做课堂练习,题目如下:
定义一个类继承于int类型,并实现一个特殊功能:
当传入的参数是字符串时,返回该字符串中所有字符的ASCII码的和。
代码如下:
class AscII(int):
def __new__(cls,str1=0):
if isinstance(str1,str):
total = 0
for each in str1:
total += ord(each)
str1 = total
return int.__new__(cls,str1)
当我不加“if isinstance(str1,str):”时,有以下报错:
Traceback (most recent call last):
File "<pyshell#12>", line 1, in <module>
print(AscII(123))
File "F:/Programming/Python/practice/41.2.py", line 4, in __new__
for each in str1:
TypeError: 'int' object is not iterable
求大佬解答!
这一行代码是用来看你传入的参数是不是字符串str类型的,如果是的话才运行
- total = 0
- for each in str1:
- total += ord(each)
- str1 = total
复制代码
你把这一行去掉以后,一旦输入的是整型int类型,就会触发
- TypeError: 'int' object is not iterable
复制代码
错误TypeError:“ int”对象不可迭代
|
|