python __getitem__,__setitem__的内

2019-07-05  本文已影响0人  远行_2a22

偶然看到类似这样的代码:

 def print_test(self):
        result = self['name'];
        print(result)

也就是说通过self[]访问类里的数据。查阅资料后,要想如此访问,必须实现__getitem__.进一步的,要想像字典一样的设置,则需要添加__setitem__

class DictDemo(object):
    def __init__(self, path=""):
        self._path = path
        self.data_dict = {
            "name": "jie",
            "age": 25,
        }
    def print_test(self, key):
        result = self[key];
        print(result)

    def __getitem__(self, item):
        result = self.data_dict.get(item)
        return result

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

my_dict = DictDemo()
my_dict.print_test("name")
my_dict["height"] = 185
my_dict.print_test("height")

参考:
python四个魔法方法len,getitem,setitem,delitem - yuan_j_y的专栏 - CSDN博客
https://blog.csdn.net/yuan_j_y/article/details/9317817

上一篇下一篇

猜你喜欢

热点阅读