python's __dict__ attribute

 A little trick to convert a dictionary into an object

bokeyuan = {"b": 1,
                "o": 2,
                "k": 3,
                "e": 4,
                "y": 5,
                "u": 6,
                "a": 7,
                "n": 8,
                }

class Dict2Obj:

    # def __init__(self, bokeyuan):
    #     self.b = bokeyuan['b']
    #     self.o = bokeyuan['o']
    #     self.k = bokeyuan['k']
    #     self.e = bokeyuan['e']
    #     self.y = bokeyuan['y']
    #     self.u = bokeyuan['u']
    #     self.a = bokeyuan['a']
    #     self.n = bokeyuan['n']

    def __init__(self, bokeyuan):
        print("修改前:", self.__dict__)
        self.__dict__.update(bokeyuan)
        print("修改后:", self.__dict__)

d = Dict2Obj(bokeyuan)
print(d)
D:\MC\venv\Scripts\py

Guess you like

Origin blog.csdn.net/weixin_42550871/article/details/124386435