如何在Python 3中遍历用户定义的类?

时间:2019-06-07 19:15:15

标签: python python-3.x

我是python的新手,正在尝试实现我在课程中学到的一些新知识,并试图定义一个字典类,该字典类具有允许其迭代并在编译时显示的功能并运行,我得到一个TypeError:对象是不可迭代的。

我正在研究pycharm,似乎无法找出问题所在。通过重写一些代码,我已经能够消除错误,但是只会导致没有输出。

class Dict:
    def __init__(self):
        self.UserDict = {}

    def __setitem__(self, key, item):
        self.__dict__[key] = item

    # def __getitem__(self, key):
        # self.__dict__[key]

    def KeyandVal(self, dic, key, val):
        dic[key] = val

    def SwapVal(self, dic, key1, key2):
        temp = ""
        temp = dic[key1]
        dic[key1] = dic[key2]
        dic[key2] = temp

    def display(self, dic): 
        for dic.UserDict.key, dic.UserDict.value in dic.UserDict:
            print(dic.UserDict[dic.UserDict.key])




choice = 1
UserDict = Dict()
while True:
    print("------------------------------")
    print("")
    print("1. Create a key and value pair")
    print("2. Change the value of a key")
    print("3. Swap key values")
    print("4. Display Dictionary")
    print("5. Export data to new file")
    print("6. Logout")
    print("")
    choice = input("Please enter a number for the desired task or '0' to Exit: ")
    if choice == "0":
        print("Thank you!")
        time.sleep(1)
        break
    elif choice == "1":
        key = input("What would you like to name this key?: ")
        val = input("What would you like its value to be?: ")
        UserDict.KeyandVal(UserDict, key, val)
    elif choice == "2":
        key = input("Which key value would you like to change?: ")
        val = input("Enter new value: ")
        UserDict.KeyandVal(UserDict, key, val)
    elif choice == "3":
        key1 = input("Enter first key: ")
        key2 = input("Enter second key: ")
        UserDict.SwapVal(UserDict, key1, key2)
        print("Values Swaped!")
    elif choice == "4":
        UserDict.display(UserDict)

优选地,一旦运行了显示功能,就应该输出键和值对。同样,什么也不会输出。

1 个答案:

答案 0 :(得分:0)

for dic.UserDict.key, dic.UserDict.value in dic.UserDict:行上,特别是在in dic.UserDict上,您隐式调用__iter__类的Dict方法,该方法未实现。这就是为什么您看到此TypeError: object is not iterable.

有关更多信息,请查看this method's docs