|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
这道题是想统计传入的参数有多少个,然后我就用两种做法来做,代码如下:
1.
class Sum:
def __init__(self,*arg):
self.len = len(arg)
if self.len == 0 :
print("并没有传入参数")
else:
print("传入了%d个参数,分别是:"%self.len,end="")
for i in arg:
print("%d "%i,end="")
2.
class Sum:
total = 0
def __init__(self,*argv):
self.List = list()
for i in argv:
self.List.append(i)
if Sum.total==0:
print("并没有传入参数")
else:
print("传入了%d个参数,分别是:"%Sum.total,end="")
for i in argv:
print("%d "%i,end="")
def __getattribute__(self,total):
Sum.total += 1
但是第二种会产生错误,为什么呢?
AttributeError: 'NoneType' object has no attribute 'append'
因为你 __getattribute__ 函数是用来获取属性,而你将这个函数没有设置怎么获取类中的属性,而你self.List.append(i) 的时候是会自动调用 __getattribute__函数来获取 self.List 这个属性
而你重写了 __getattribute__ 而且没有设置返回值,导致你访问类中的属性时候返回的值为 None
而 None 没有列表的这种函数方法 append ,导致报错,所以你只需要在你 __getattribute__ 调用下父类方法即可,代码如下:
- class Sum:
- total = 0
- def __init__(self,*argv):
- self.List = list()
- for i in argv:
- self.List.append(i)
- if Sum.total==0:
- print("并没有传入参数")
- else:
- print("传入了%d个参数,分别是:"%Sum.total,end="")
- for i in argv:
- print("%d "%i,end="")
- def __getattribute__(self,total):
- Sum.total += 1
- return super().__getattribute__(total) # 这里调用父类的 __getattribute__ 方法即可正常运行
- a = Sum(1,2,3,4,5)
复制代码
输出结果:
|
|