direct initialization of class attributes vs. declarations w/in __init__

digitalorganics at gmail.com digitalorganics at gmail.com
Sun Jun 11 17:46:53 EDT 2006


Thank you Dennis, this makes the behavior so much clearer to me. I see
now that when  self.jerk = self.jerk + 1 is executed that even though
the names are identical, at this point I'm referring to two different
values (one which is being created in part from the other).

As for my laptop, I'm not really sure what's up there. I can change the
class variable self.jerk all I want but it has no influence over the
instance variable.  Here's the code:

class Boo:
    jerk = 10

    def killjerk(self):
        self.jerk += 1
        print self.jerk
        print self.__class__.jerk

bing = Boo()
bing.killjerk()

On my desktop, I get:

11
10

On my laptop, I get:

1
10

Now, if I remove the class variable, I get an AttributeError, as you'd
expect. This happens on both the desktop and laptop. However, on the
laptop it seems not to care what value I give the class variable jerk,
it only requires that it exist. Any clue what's behind this behavior?
I'm running the same python version on both computers (the ActiveState
distro).

Thanks for all the help...


Dennis Lee Bieber wrote:
> On 11 Jun 2006 10:35:14 -0700, digitalorganics at gmail.com declaimed the
> following in comp.lang.python:
>
> > Wait a minute! It doesn't explain my bugs. I've got "class variables"
> > acting like instance variables. What's weirder is that this behavior
> > occurs on my computer (in both of my installed WinXP copies) but not on
> > my laptop (WinXP Pro).
> >
> 	Don't know about the laptop but...
>
> > See the following test:
> >
> 	See the following modified version:
>
> -=-=-=-=-=-=-
> class Boo:
>     jerk = "yes"
>
>     def killjerk(self):
>         print id(self.jerk), id(self.__class__.jerk)
>         self.jerk = self.jerk + "no"
>         print self.jerk, id(self.jerk)
>         print self.__class__.jerk
>
> bing = Boo()
> bing.killjerk()
> bing.killjerk()
> -=-=-=-=-=-=-=-
> 10837696 10837696
> yesno 18264128
> yes
> 18264128 10837696
> yesnono 18289600
> yes
>
> 	The initial lookup for "self.jerk" does not find it in the instance,
> so it looks higher, into the class.
>
> 	THEN when you "assign" the result to "self.jerk" you create an
> instance specific name entry, which is bound to a string at a different
> location. The lookup on the left side does not go outside of the
> instance. Notice how the second "bing.killjerk()" results in "self.jerk"
> being bound to a third address.
>
> --
> 	Wulfraed	Dennis Lee Bieber		KD6MOG
> 	wlfraed at ix.netcom.com		wulfraed at bestiaria.com
> 		HTTP://wlfraed.home.netcom.com/
> 	(Bestiaria Support Staff:		web-asst at bestiaria.com)
> 		HTTP://www.bestiaria.com/




More information about the Python-list mailing list