__init__ & attributes clarification

Bengt Richter bokr at oz.net
Mon Feb 3 07:58:27 CET 2003


On Sun, 02 Feb 2003 23:00:20 GMT, Afanasiy <abelikov72 at hotmail.com> 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"

Does the following help?

 >>> class C:
 ...     def setInstAttr(self, name, value): setattr(self, name, value)
 ...     def setClassAttr(self, name, value): setattr(self.__class__, name, value)
 ...
 >>> c=C()
 >>> vars(c)
 {}
 >>> vars(C)
 {'__module__': '__main__', '__doc__': None, 'setInstAttr': <function setInstAttr at 0x007A8980>,
  'setClassAttr': <function setClassAttr at 0x007A97E0>}
 >>> c.setInstAttr('x','instance attr')
 >>> vars(c)
 {'x': 'instance attr'}
 >>> vars(C)
 {'__module__': '__main__', '__doc__': None, 'setInstAttr': <function setInstAttr at 0x007A8980>,
  'setClassAttr': <function setClassAttr at 0x007A97E0>}
 >>> c.setClassAttr('x','class attr')
 >>> vars(c)
 {'x': 'instance attr'}
 >>> vars(C)
 {'x': 'class attr', '__module__': '__main__', '__doc__': None, 'setInstAttr': <function setInstA
 ttr at 0x007A8980>, 'setClassAttr': <function setClassAttr at 0x007A97E0>}
 >>> c.x
 'instance attr'
 >>> C.x
 'class attr'

Regards,
Bengt Richter




More information about the Python-list mailing list