后续问题这个问题 https://stackoverflow.com/questions/50375793/elegant-way-to-have-an-almost-copy-constructor-that-allows-to-update-some-member:我在 python 3.5 和 python 3.6 上运行了下面的代码 - 得到了非常不同的结果:
class Container:
KEYS = ('a', 'b', 'c')
def __init__(self, a=None, b=None, c=None):
self.a = a
self.b = b
self.c = c
def keys(self):
return Container.KEYS
def __getitem__(self, key):
if key not in Container.KEYS:
raise KeyError(key)
return getattr(self, key)
def __str__(self):
# python 3.6
# return f'{self.__class__.__name__}(a={self.a}, b={self.b}, c={self.c})'
# python 3.5
return ('{self.__class__.__name__}(a={self.a}, b={self.b}, '
'c={self.c})').format(self=self)
data0 = Container(a=1, b=2, c=3)
print(data0)
data3 = Container(**data0, b=7)
print(data3)
正如上一个问题所述,这引发了
类型错误:类型对象获得关键字参数“b”的多个值
在Python 3.6上。但在 python 3.5 上我得到了异常:
密钥错误:0
此外,如果我不加注KeyError
但只需打印出key
and return
in __getitem__
:
def __getitem__(self, key):
if key not in Container.KEYS:
# raise KeyError(key)
print(key)
return
return getattr(self, key)
这将打印出int
顺序0, 1, 2, 3, 4, ...
。 (蟒蛇3.5)
所以我的问题是:
版本之间发生了什么变化导致其行为如此不同?
这些整数从哪里来?
UPDATE: 正如评论中提到的λuser https://stackoverflow.com/users/6541288/%ce%bbuser:实施__iter__
将更改 python 3.5 上的行为以匹配 python 3.6 的行为:
def __iter__(self):
return iter(Container.KEYS)