天天看點

将對象當作字典操作

class People(object):
    def __init__(self, name, age):
        self.name = name
        self.age = age

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

    def __getitem__(self, item):
        return self.__dict__[item]


handsome = People("靓仔", 18)

# print(handsome.name)
handsome["age"] = 20  # 調用__setitem__方法,修改對象屬性
handsome["name"] = "beefcake"
print(handsome.age)
print(handsome.name)
print("-" * 20)
print(handsome["age"])  # 調用__getitem__方法,調用對象屬性
print(handsome["name"])
print("-" * 20)
print(handsome.__dict__)  # 将對象轉化為字典      

繼續閱讀