python

【面试题】操作符与内置方法

文章暂存

systemime
2020-10-21
1 min

摘要.

# 请写一个类继承dict类,支持.方式访问

mydict = Mydict()
mydict.a = 1
mydict.b = 2
mydict.c.d = 3
print mydict
print mydict.c
输出:
{'a': 1, 'c': {'d': 3}, 'b': 2}
{'d': 3}


解法

# 解法1
class Mydict(dict):
    def __setattr__(self,key,value):
        self[key] = value

    def __getattr__(self,key):
        try:
            return self[key]
        except:
            self[key] = Mydict()
            return self[key]

# # 解法2
# class My_dict(dict):
#
#     def __getattr__(self, key):
#         try:
#             return self.__dict__[key]
#         except:
#             self.__dict__[key] = My_dict()
#             return self.__dict__[key]
#
#     def __repr__(self):
#         return repr(self.__dict__)

# # 解法3
# class MyDict(dict):
# 
#     def __setattr__(self, key, value):
#         self[key] = value
# 
#     def __getattr__(self, key):
#         try:
#             return self[key]
#         except KeyError:
#             return self.setdefault(key, MyDict())


m = Mydict()
# m = My_dict()
m.a = 1
m.b = 2
m.c.d = 4
print(m)


上次编辑于: 2021/5/20 下午3:26:49