Class attributes newbie question (before I join a cargocult)

Peter Otten __peter__ at
Mon Mar 13 08:52:38 CET 2006

EP wrote:

> This is likely a stupid question, 

There seems to be a cult believing that calling one's own question "stupid"
magically diminishes its degree of stupidity. In reality, as a compiler
would put it, "code has no effect".

> but I am confused about what is going 
> on with class attributes as far as whether they "stick".  I ran across
> this in a program I am writing, but have reproduced the behavoir below
> - can someone point me in the right direction (thanks):
> class AttStickiness(object):
>     def __init__(self, myname="", mysex=""):
>     def changeSex(self, newsex=""):
>         self.mysex=newsex
>         return self.mysex
>     def changeName(self, newname=""):
>         return
>     def whoAmI(self):
>         return, self. sex

Are empty strings reasonable defaults for name or sex? No.
Do the changeXXX() methods /conceptionally/ anything except change an
attribute? No.
Is whoAmI() meant to inform the user/developer? Yes.

If your answers were like mine you are already deeply into "cargocult".
Instead of changeXXX() use attributes directly (you can turn them into
properties should side effects become necessary), instead of whoAmI() use
__str__() or __repr__().
>>> class Person(object):
...     def __init__(self, name, sex):
...    = name
...    = sex
...     def __repr__(self):
...             return "Person(name=%r, sex=%r)" % (,
>>> me = Person("Eric", "male")
>>> me
Person(name='Eric', sex='male')
>>> = "Jimbo"
>>> me
Person(name='Jimbo', sex='male')
>>> = "female"
>>> me
Person(name='Jimbo', sex='female')


More information about the Python-list mailing list