Understanding the pythonic way: why a.x = 1 is better than a.setX(1) ?

Ivan Illarionov ivan.illarionov at gmail.com
Thu Sep 4 15:15:16 EDT 2008


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.
>
> Carl Banks

'__slots__' is better:
class A(object):
    __slots__ = set(["x"])
    def __init__(self, x):
        self.y = x

this will do the same, only faster
>>> A(1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in __init__
AttributeError: 'A' object has no attribute 'y'


Ivan Illarionov



More information about the Python-list mailing list