An object that creates (nested) attributes automatically on assignment

Steven D'Aprano steve at REMOVE-THIS-cybersource.com.au
Sat Apr 11 07:54:35 EDT 2009


On Sat, 11 Apr 2009 03:01:48 -0700, Edd wrote:

> Yes I probably mean instance attributes. Forgive me, I am not
> particularly sure of the terminology. But your MyClass example, won't
> quite do what I want, as I'd like to be able to define instance
> attributes on top of instance attributes by assignment:
> 
>>>> class MyClass(): pass
> ...
>>>> instance = MyClass()
>>>> instance.lasers.armed = True
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> AttributeError: MyClass instance has no attribute 'laser'

Ah, now it is more clear.

Okay, let's try this:


>>> class C(object):
...     def __getattr__(self, name):
...             # Only called if self.name doesn't exist.
...             inst = self.__class__()
...             setattr(self, name, inst)
...             return inst
...
>>> c = C()
>>> c.x.y.z = 45
>>> c.__dict__
{'x': <__main__.C object at 0xb7c3b78c>}
>>> c.x.__dict__
{'y': <__main__.C object at 0xb7c3b7ec>}
>>> c.x.y.z
45



-- 
Steven



More information about the Python-list mailing list