osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Dunder variables


On Tue, 09 Jan 2018 16:14:27 +0200, Frank Millman wrote:

> Maybe I was not clear. The Context instance is passed as an argument to
> many methods. The methods can access the attributes of the instance. The
> instance has no methods of its own.

Ah, I see, I misunderstood.


[...]
>> Alternatively, use a SimpleNamespace:
> 
> I did play with that for a while, but AFAIK it does not allow you to
> define read-only attributes.


Not directly, no, but you can subclass:

py> class Spam(SimpleNamespace):
...     @property
...     def eggs(self):
...             return "foo"
...
py> bag = Spam()
py> bag.eggs
'foo'
py> bag.eggs = 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: can't set attribute


However, at the point you are subclassing and adding multiple properties, 
I'm not sure there's any advantage over just defining a class from 
scratch. While it is true that SimpleNamespace gives you a nice repr, the 
properties don't show up in that repr, and I assume it is those read-only 
attributes that you most care about.


-- 
Steve