Class Variable Access and Assignment

Steven D'Aprano steve at REMOVETHIScyber.com.au
Fri Nov 4 13:02:05 EST 2005


On Fri, 04 Nov 2005 08:08:42 +0000, Antoon Pardon wrote:

> One other way, to implement the += and likewise operators would be
> something like the following.
> 
> Assume a getnsattr, which would work like getattr, but would also
> return the namespace where the name was found. The implementation
> of b.a += 2 could then be something like:
> 
>   ns, t = getnsattr(b, 'a')
>   t = t + 2
>   setattr(ns, 'a')
> 
> 
> I'm not arguing that this is how it should be implemented. Just
> showing the implication doesn't follow.

Follow the logical implications of this proposed behaviour.

class Game:
    current_level = 1
    # by default, games start at level one  
    
    def advance(self):
        self.current_level += 1


py> antoon_game = Game()
py> steve_game = Game()
py> steve_game.advance()
py> steve_game.advance()
py> print steve_game.level
3
py> print antoon_game.level

What will it print?

Hint: your scheme means that class attributes mask instance attributes.


-- 
Steven.




More information about the Python-list mailing list