Accessing Dictionary Members via Dot Notation in Python
Python dictionaries typically provide access to their members using square brackets ([]). To enable dot notation (.) for accessing members, consider the following approach:
Utilizing the dotdict Class:
A common solution involves creating a custom class called dotdict, which extends the built-in dict class. This class provides the necessary getattr__, __setattr__, and __delattr methods to support dot notation access.
Here's an example implementation:
class dotdict(dict): """dot.notation access to dictionary attributes""" __getattr__ = dict.get __setattr__ = dict.__setitem__ __delattr__ = dict.__delitem__
Using dotdict:
To use dotdict, convert your existing dictionaries into instances of the dotdict class. This enables access to members using dot notation:
mydict = {'val':'it works'} nested_dict = {'val':'nested works too'} mydict = dotdict(mydict) mydict.val # 'it works' mydict.nested = dotdict(nested_dict) mydict.nested.val # 'nested works too'
By using dotdict, you can conveniently access dictionary members using the more intuitive dot notation. Nested dictionaries can also be accessed in this manner by creating nested dotdict instances.
以上是如何使用點表示法存取 Python 字典的成員?的詳細內容。更多資訊請關注PHP中文網其他相關文章!