Robot限制字典的key大写的class


# 类的定义
class RobotObjectDict(dict):

    def __getattr__(self, attr):
        value = self[str(attr).upper()]
        return RobotObjectDict(value) if isinstance(value, dict) else value

    def __setattr__(self, name, value):
        self[str(name).upper()] = value

    def __delattr__(self, name):
        del self[name]

#函数
def get_variables(target=""):
    dest_dict = {}  # 返回的是普通的dict
    for varname, varvalue in globals().items():
        if varname.isupper():
            if target:
                varname=target+'_'+varname
            dest_dict[varname] = RobotObjectDict(varvalue) if \
            isinstance(varvalue, dict) else varvalue
    return dest_dict


a = RobotObjectDict({'AA':'cc'})  # a 是RobotObjectDict加工后的字典类型
b = RobotObjectDict({'bb':'cc'})
D = RobotObjectDict({'bb':'cc'})
E = 1
f = 2
V = {
       'REMOTE_LIBRARY_HOST_IP': 'x',
       'UNIT_DEVICE_IP': ['y', 'z'],
       'xiao':123,
       'DA':45,
      }


# 正确设置
a['TT'] = 'bb'

# 错误使用
# a['aa'] = 'aa' # 这样测试值,调用会报错
# print(a.AA)    # 调用会报错 ,因为‘AA’对应的值不存在
# print(a['tt']) # 调用会报错,因为‘tt’对应的值不存在
# 错误使用
# print(a.bb)

# 正确调用
# print(a.tt)     # 调用 __getattr__ ,字典就返回 a['TT']的值
# print(a.TT)     # 调用 __getattr__ ,字典就返回 a['TT']的值
# 正确调用
# print(a.aa)

# 正确调用
# a.test = 'test'
# print(a.test)
# print(a.TEST)


v_dic =get_variables('amize')
# v_dic =get_variables('')
print(v_dic)  # 所有全局变量
print(v_dic['amize_V'])  # 普通的dict,只能用[]调用
# 错误调用
# print(v_dic['amize_V'].da)  # 不能用小写调用
print(v_dic['amize_V'].DA)


原文地址:https://www.cnblogs.com/amize/p/14363482.html