Class attributes newbie question (before I join a cargocult)

Peter Otten __peter__ at web.de
Mon Mar 13 02:52:38 EST 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=""):
>         self.name=myname
>         self.sex=mysex
> 
>     def changeSex(self, newsex=""):
>         self.mysex=newsex
>         return self.mysex
> 
>     def changeName(self, newname=""):
>         self.name=newname
>         return self.name
> 
>     def whoAmI(self):
>         return self.name, 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):
...             self.name = name
...             self.sex = sex
...     def __repr__(self):
...             return "Person(name=%r, sex=%r)" % (self.name, self.sex)
...
>>> me = Person("Eric", "male")
>>> me
Person(name='Eric', sex='male')
>>> me.name = "Jimbo"
>>> me
Person(name='Jimbo', sex='male')
>>> me.sex = "female"
>>> me
Person(name='Jimbo', sex='female')

Peter



More information about the Python-list mailing list