Can Python Dictionaries Emulate Object Attributes?
Accessing dictionary keys as object attributes offers convenience, but raises questions about potential issues. This article explores the usage of AttrDict, a custom class designed to address this need.
Custom Class Approach
To emulate object attributes for a dictionary, one can create a subclass called AttrDict:
class AttrDict(dict): def __getattr__(self, attr): return self[attr] def __setattr__(self, attr, value): self[attr] = value
Advantages of the Custom Class
Disadvantages of the Custom Class
How it Works
The AttrDict class assigns itself as the internal __dict__ attribute of the object. This links the dictionary namespace to the object's attributes, allowing access via both syntaxes.
Python's Rationale for Not Providing This Feature
Python avoids the direct attribute access feature to prevent namespace pollution. Assigning dictionary items can potentially override method attributes, leading to unexpected behavior. For example:
d = AttrDict() d.update({'items': ['jacket', 'necktie', 'trousers']}) for k, v in d.items(): # TypeError: 'list' object is not callable
The above is the detailed content of Can Python Dictionaries Be Used Like Objects?. For more information, please follow other related articles on the PHP Chinese website!