对象中使用索引操作, 魔法方法__getitem__、__setitem__、__delitem__的使用

代码

# 定义一个类字典对象(继承于dict类),
# 创建一个类字典对象,键“a”的值为1,键“b”的值为2.
# 当访问键"a"的值得时候,屏幕打印100,
# 注意这里不是修改字典。
# 修改键“b”的值得时候,屏幕打印键“b”和修改后的值,
# 最后打印修改之后的字典。


class DiyDict(dict):
	"""定义一个类字典对象(继承于dict类)"""

    def __init__(self, dict_item, **kwargs):
        # super调用父类的方法
        super().__init__(dict_item, **kwargs)

    def __getitem__(self, key):
        """当访问键"a"的值得时候,屏幕打印100"""
        if key == "a":
            print('当访问键"a"的值得时候,屏幕打印100')
            # 这里的返回值当作 dict[key]的返回值
            return 100
        else:
            return super().__getitem__(key)

    def __setitem__(self, key, value):
        """修改键“b”的值得时候,屏幕打印键“b”和修改后的值"""
        if key == "b":
            print("{}:{}".format(key, value))
        super().__setitem__(key, value)

    def __delitem__(self, key):
        """当删除键时"""
        print("in __delitem__ function, and it's deleting the key>>>'{}' now".format(key))
        super().__delitem__(key)


if __name__ == '__main__':
    # 创建一个类字典对象,键“a”的值为1,键“b”的值为2.
    diy_dict = DiyDict({
    
    "a": 1, "b": 2})
    print("-" * 30, "测试当访问key为'a'时")
    print(diy_dict["a"])

    print("-" * 30, "测试当修改key为'b'时")
    print(diy_dict["b"])
    diy_dict["b"] = 500
    
    print("-" * 30, "测试其它键值对")
    diy_dict["d"] = 700
    print(diy_dict["d"])

    print("-" * 30, "打印字典")
    print(diy_dict)

    print("-" * 30, "测试删除键")
    del diy_dict["a"]
    print(diy_dict["a"])

    print("-" * 30, "打印字典")
    print(diy_dict)


运行结果

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/u010684603/article/details/108893908