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

Carl Banks pavlovevidence at gmail.com
Thu Sep 4 14:59:43 EDT 2008


On Sep 4, 7:09 am, "Marco Bizzarri" <marco.bizza... at gmail.com> wrote:
> Sorry... pressed enter but really didn't want to.
>
> As I said, let's say I have a class
>
> class A:
>     def __init__(self):
>          self.x = None
>
> Python makes the decision to allow the developers to directly access
> the attribute "x",  so that they can directly write: "a.x = 1", or
> whatever; this has for me the unfortunate side effect that if I write,
> for example "a.y = 1", when I really wanted to write "a.x = 1" no one
> cares about it, and I'm unable to spot this error until later.


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



More information about the Python-list mailing list