Home > Mobile >  Why can't call the dictionary's value with its key?
Why can't call the dictionary's value with its key?

Time:10-13

We can call value in a dictionary with its key.

class mymodel(type):
    _instances = {}
    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super().__call__(*args, **kwargs)
        return cls._instances[cls]

class mytest(object,metaclass=mymodel):
    pass

Check its attribution.

mytest._instances
{}

Call mytest first time to let it contain an attribution _instances.

mytest()
<__main__.mytest object at 0x7f3286774b20>
mytest._instances
{<class '__main__.mytest'>: <__main__.mytest object at 0x7f3286774b20>}
type(mytest._instances)
<class 'dict'>
mytest._instances.keys()
dict_keys([<class '__main__.mytest'>])

Call its value with key:

mytest._instances[<class '__main__.mytest'>]
  File "<stdin>", line 1
    mytest._instances[<class '__main__.mytest'>]
                      ^
SyntaxError: invalid syntax
mytest._instances["<class '__main__.mytest'>"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: "<class '__main__.mytest'>"

Try to escape with backslash \:

mytest._instances[\<class '__main__.mytest'\>]
  File "<stdin>", line 1
SyntaxError: unexpected character after line continuation character
mytest._instances["\<class '__main__.mytest'\>"]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: "\\<class '__main__.mytest'\\>"

How can call the value in mytest._instances with key then?

CodePudding user response:

That's not a string, it's an class object.

You should use:

mytest._instances[mytest]

CodePudding user response:

When you look at mytest._instances, it is showing you what the dictionary contains:

mytest._instances
    {<class '__main__.mytest'>: <__main__.mytest object at 0x7f3286774b20>}

i.e. the dictionary key is mytest's class and the dictionary value is a specific instance of my test

So you can get the value by using:

mytest._instances[mytest]
    <__main__.mytest object at 0x7f3286774b20>
  • Related