ValueError: too many values to unpack (expected 2)


class Mymeta(type):
    def __new__(cls, class_name, class_bases, class_attrs):
        print('--->', cls)  # ---> <class '__main__.Mymeta'>
        print('--->', class_name)  # ---> Chinese
        print('--->', class_bases)  # ---> (<class 'object'>,)
        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():


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM