( )、[ ]、{ }这三个,分不清什么时候需要用,或者需要用哪个
本帖最后由 lzb1001 于 2022-3-16 16:28 编辑class Rectangle:
def __init__(self, width=0, height=0):
self.width = width
self.height = height
def __setattr__(self, name, value):
if name == 'square':
self.width = value
self.height = value
else:
self.__dict__ = value # 1:为何这里用[],不用( )或用下面3返回的{ }?
def getArea(self):
return self.width * self.height
运行后:
>>> r1 = Rectangle(4, 5)
>>> r1.square = 6
>>> r1.__dict__ # 2:为何这里什么括号都不需要,加了括号反而返回错误,像下面的4?
{'width': 6, 'height': 6} # 3
>>> r1.__dict__() # 4
Traceback (most recent call last):
File "<pyshell#14>", line 1, in <module>
r1.__dict__()
TypeError: 'dict' object is not callable
小括号是函数,元组
中括号是列表,数组
花括号是c语言里的,字典 1.只能用[],不然报错
2.
r1.__dict__ # 2:为何这里什么括号都不需要,加了括号反而返回错误,像下面的4?
因为__dict__ 是字典,不是函数 "()"一般用于输入函数的参数
"[]"是列表
"{}"是字典
页:
[1]