__init__ & attributes clarification

Alex Martelli aleax at aleax.it
Mon Feb 3 02:40:50 EST 2003


Afanasiy wrote:

> On Sun, 02 Feb 2003 22:36:26 GMT, Alex Martelli <aleax at aleax.it> wrote:
> 
>>Afanasiy wrote:
>>    ...
>>> This is unusual in my experience... So, if an object writes to a member
>>> with the same name as a class member, does it change that class member
>>> for the class, all instances of the class, all future instances, or just
>>> self?
>>
>>"writes to" is ambiguous -- can mean "rebind" or "modify" (e.g.,
>>call the .append method on a list object) -- two totally different
>>cases, of course.
> 
> I mean setting, as in "setattr"

Still ambiguous (my compliments: it's not easy to manage to be
exactly this ambiguous twice in succession with different wording).

case 1:

class Bunch: pass

class GuessWhat:
    b = Bunch()
    def dosomesetting(self):
        setattr(self.b, 'foo', 'bar')

Here, calling method dosomething on any instance of GuessWhat
does the "setting" on the one and only instance of Bunch that
all instances of GuessWhat share -- there IS no other instance
of Bunch around.

case 2:

class Subtler:
    xx = 23
    def setinself(self): setattr(self, 'xx', 45)
    def setinclass(self): setattr(Subtler, 'xx', 67)

Here, given an instance x of class Subtler, calling
x.setinself() sets attribute 'xx' in x itself (as I
hope would be pretty clear from the first argument
to setattr), calling x.setinclass() sets attribute
'xx' in class Subtler.  Any instance y of Subtler uses
that one and only Subtler.xx, when you _access_, i.e.,
"read", y.xx -- if and only if y has no per-instance
attribute also named 'xx'.

These calls to setattr are fully equivalent to the
normal assignment-statement syntax, self.xx=45 and
Subtler.xx=67 respectively.  There is no reason to
use setattr when the name is a constant, although of
course it is not forbidden, either.

Anyway, I hope the use of self to affect self,
and Subtler to affect Subtler, is clear enough.


I suggest you use the common Python terminology,
"binding" when you are affecting what object
a name refers to, and "mutating" when you are
not affecting names but rather changing an object.
This terminology is admittedly not universal, but
I think it's widespread enough that using it may
help avoid miscommunication and ambiguity.


Alex





More information about the Python-list mailing list