Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ?
ivan.illarionov at gmail.com
Sat Sep 6 02:09:44 CEST 2008
On 5 сент, 19:23, "Diez B. Roggisch" <de... at nospam.web.de> wrote:
> Ivan Illarionov schrieb:
> > On 4 сент, 21:49, Bruno Desthuilliers
> > <bdesth.quelquech... at free.quelquepart.fr> wrote:
> >> Ivan Illarionov a écrit :
> >>> On 4 сент, 22:59, Carl Banks <pavlovevide... at gmail.com> wrote:
> >>>> You can write code to guard against this if you want:
> >>>> class A:
> >>>> legal = set(["x"])
> >>>> def __setattr__(self,attr,val):
> >>>> if attr not in self.legal:
> >>>> raise AttributeError("A object has no attribute '%s'" %
> >>>> attr)
> >>>> self.__dict__[attr] = val
> >>>> def __init__(self,x):
> >>>> self.y = x
> >>>> I suspect most people who go into Python doing something like this
> >>>> soon abandon it when they see how rarely it actually catches anything.
> >>> '__slots__' is better:
> >> For which definition of "better" ? __slots__ are a mean to optimize
> >> memory usage, not to restrict dynamism. Being able to dynamically add
> >> arbitrary attributes is actually a feature, not a bug, and uselessly
> >> restricting users from doing so is not pythonic. IOW : don't do that.
> > Carl's example is restricting dynamism in the same way as __slots__.
> > I've just suggested a better implementation. It is not me who
> > suggested dynamism restriction as a way to guard against errors.
> This is not correct. While Carl's Example looks similar, you actually
> *can* create new attributes using
> obj.__dict__['name'] = value
> __slots__ OTOH prevents that because it does create instances *without*
> an instance-dict.
> This being said, I think we all agree that it's nothing to be desired.
+1 for unit tests as a way to guard against errors.
Bot sometimes __slots__ is exactly what I want (for other reasons) and
I like to avoid __getattr__ hacks in any situation.
More information about the Python-list