class Mymeta(type): def __new__(cls, class_name, class_bases, class_attrs): print('--->', cls) # --->print('--->', class_name) # ---> Chinese print('--->', class_bases) # ---> ( ,) print('--->', class_attrs) # 'Chinese', 'country': 'china', 'skin': 'yello', '__init__': .... print(class_attrs.items()) update_attrs = {} for key, value in class_attrs: if not callable(value) and not key.startswith('__'): update_attrs[key.upper()] = value else: update_attrs[key] = value return type.__new__(cls, class_name, class_bases, update_attrs)class Chinese(object, metaclass=Mymeta): country = 'china' skin = 'yello'
返回了下面的错误:
for key, value in class_attrs:ValueError: too many values to unpack (expected 2)
原因是字典这个是一个迭代器对象,参考官方文档找到下列说明,字典只支持Key的遍历,,如果想对key,value,则可以使用items方法。
The “implicit” iteration that dictionaries support only iterates over keys.python只支持对于key的遍历,所以不能使用for k,v这种形式,这个时候会提示ValueError: too many values to unpack,
正确代码如下:for key, value in class_attrs.items():