从字典中的自定义函数访问值

时间:2019-04-23 11:41:47

标签: python python-2.7

对于特定的用例,我有以下几行代码。 (使用python 2.7)

class AutoMap(dict):
    """Implementation of autovivification feature."""
    def __getitem__(self, item):
        try:
            return dict.__getitem__(self, item)
        except KeyError:
            value = self[item] = type(self)()
            return value
    def __dir__(self):
        return dict.keys()
    __getattr__ = dict.get
    __setattr__ = dict.__setitem__
    __delattr__ = dict.__delitem__

obj = AutoMap()
AddressMap = AutoMap()

obj["state"] = "Maharastra"
obj["country"] = "India"

AddressMap['address1'] = obj

obj["state"] = "California"
obj["country"] = "USA"

AddressMap['address2'] = obj

print AddressMap # {'address1': {'state' : 'Maharastra', 'country' : 'India'}, 'address2': {'state' : 'California', 'country' : 'USA'}}

def prn_state():
    print "State: " + state


AddressMap['address1']['_prn_state'] = prn_state

AddressMap['address2']['_prn_state'] = prn_state


print AddressMap # {'address1': {'state' : 'Maharastra', 'country' : 'India', '_prn_state': <function prn_state at 0x7fb297dc7320>}, 'address2': {'state' : 'California', 'country' : 'USA', '_prn_state': <function prn_state at 0x7fb297dc7320>}}

print type(AddressMap) # <class 'AutoMap'>

print AddressMap.address2._prn_state()

现在,我希望每当我编写此行代码时,都应打印“ California”。 但是,它抛出一个错误,提示“ NameError:未定义全局名称'state'”

3 个答案:

答案 0 :(得分:2)

File file = new File(path); Scanner scanner = new Scanner(file); Map<String, User> userdb = new TreeMap<>(); while (scanner.hasNextLine()) { String line = scanner.nextLine(); String ip = line.split(";")[0]; String id = line.split(";")[1]; String fio = line.split(";")[2]; String adress = line.split(";")[3]; User user = new User(id, fio, adress); userdb.put(id, user); } scanner.close(); AddressMap,以获取dict的{​​{1}}值:

state

编辑

包装在函数中

address2

输出

AddressMap = {'address1': {'state' : 'Maharastra', 'country' : 'India'}, 
              'address2': {'state' : 'California', 'country' : 'USA'}}    
print(AddressMap['address2']['state'])

答案 1 :(得分:1)

错误告诉您,state未在全局上下文中定义。 工作正常:

class AutoMap(dict):
    """Implementation of autovivification feature."""
    def __getitem__(self, item):
        try:
            return dict.__getitem__(self, item)
        except KeyError:
            value = self[item] = type(self)()
            return value
    def __dir__(self):
        return dict.keys()
    __getattr__ = dict.get
    __setattr__ = dict.__setitem__
    __delattr__ = dict.__delitem__

    def prn_state(self):
        print "State: " + self.state

obj = AutoMap()
AddressMap = AutoMap()

obj["state"] = "Maharastra"
obj["country"] = "India"

AddressMap['address1'] = obj

obj["state"] = "California"
obj["country"] = "USA"

AddressMap['address2'] = obj

print AddressMap

AddressMap['address1']['_prn_state'] = AddressMap['address1'].prn_state

AddressMap['address2']['_prn_state'] = AddressMap['address2'].prn_state


print AddressMap

print type(AddressMap)

AddressMap.address2._prn_state()

答案 2 :(得分:0)

class AutoMap(dict):
    """Implementation of perl's autovivification feature."""
    def __getitem__(self, item):
        try:
            return dict.__getitem__(self, item)
        except KeyError:
            value = self[item] = type(self)()
            return value
    def __dir__(self):
        return dict.keys()

    __getattr__ = dict.get
    __setattr__ = dict.__setitem__
    __delattr__ = dict.__delitem__


class Sample:
    def __init__(self, d): 
        self.test = d
    def prn_state(self): 
        print self.test.state

obj = AutoMap()
AddressMap = AutoMap()

obj["state"] = "Maharastra"
obj["country"] = "India"
obj["sample"] = Sample(obj)
AddressMap['address1'] = obj

obj["state"] = "California"
obj["country"] = "USA"
obj["sample"] = Sample(obj)
AddressMap['address2'] = obj

AddressMap.address2.sample.prn_state()