Class attributes newbie question (before I join a cargocult)

pclinch at internet-glue.co.uk pclinch at internet-glue.co.uk
Sun Mar 12 13:53:57 EST 2006


EP wrote:
> Hi,
>
> This is likely a stupid question, 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
>

You might want self.sex = newsex and return self.sex here.

See __slots__ and PyChecker for possible ways to avoid misspelled
instance variables.

>     def changeName(self, newname=""):
>         self.name=newname
>         return self.name
>
>     def whoAmI(self):
>         return self.name, self. sex
>
> >>> me=AttStickiness("Eric","Male")
>
> >>> me.whoAmI()
> ('Eric', 'Male')
>
> >>> me.changeName("Jimbo")
> 'Jimbo'
>
> >>> me.whoAmI()
> ('Jimbo', 'Male')
>
> >>> me.changeSex("female")
> 'female'
>
> >>> me.whoAmI()
> ('Jimbo', 'Male')
>
>
> [while it is comforting to know my sex isn't so easily changed, this
> has confounded me in real code]
> 
> thx,
> 
> Eric

Regards, Paul




More information about the Python-list mailing list