Class Variable Access and Assignment

Mike Meyer mwm at mired.org
Sat Nov 5 00:00:51 EST 2005


Paul Rubin <http://phr.cx@NOSPAM.invalid> writes:
> Steven D'Aprano <steve at REMOVETHIScyber.com.au> writes:
>> It also allows you to do something like this:
>> class ExpertGame(Game):
>>     current_level = 100
>
>> and then use ExpertGame anywhere you would have used Game with no problems.
> Well, let's say you set, hmm, current_score = 100 instead of current_level.
> Scores in some games can get pretty large as you get to the higher
> levels, enough so that you start needing long ints, which maybe are
> used elsewhere in your game too, like for the cryptographic signatures
> that authenticate the pieces of treasure in the dungeon.  Next you get
> some performance gain by using gmpy to handle the long int arithmetic,
> and guess what?  Eventually a version of your game comes along that
> enables the postulated (but not yet implemented) mutable int feature
> of gmpy for yet more performance gains.  So now, current_score += 3000
> increments the class variable instead of creating an instance
> variable, and whoever maintains your code by then now has a very weird
> bug to track down and fix.

I'd say that's a wart with +=, not with Python's inheritance
mechanisms. += is neither + nor =, but takes on different aspects of
each depending on what it's operating on. While it's true that python
is dynamic enough that the you can create classes that make this true
for any operator, += is the only one that acts like that on the
builtin types.

        <mike
-- 
Mike Meyer <mwm at mired.org>			http://www.mired.org/home/mwm/
Independent WWW/Perforce/FreeBSD/Unix consultant, email for more information.



More information about the Python-list mailing list