Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #97201

Re: Question re class variable

Date 2015-09-29 12:40 +0200
From Antoon Pardon <antoon.pardon@rece.vub.ac.be>
Subject Re: Question re class variable
References <3948d9cd-24b1-4a3b-8ed0-46bb60a8d738@googlegroups.com>
Newsgroups comp.lang.python
Message-ID <mailman.232.1443523293.28679.python-list@python.org> (permalink)

Show all headers | View raw


Op 29-09-15 om 11:27 schreef plewto@gmail.com:
> I have a perplexing problem with Python 3 class variables. I wish to generate an unique ID each time an instance of GameClass is created. There are two versions of the __gen_id method with test run results for each listed below the code.

The problem is that in python you can't change a class variable through an instance. The moment you
try, you create an instance attribute.

> class GameObject:
>
>     # __instance_registry = {"":None}
>     __instance_counter = 0
>     
>     def __init__(self, name):
>         self.__name = str(name)
>         self.__id = self.__gen_id()
>
>     def __gen_id(self):
>         ty = self.__class__.__name__
>         id = '%s_%d' % (ty, self.__instance_counter)
>         self.__instance_counter += 1

This last line doesn't work as expected. What happens is equivallent to
the following.

          self.__instance_counter = self.__instance_counter + 1

But the self.__instance_counter are two different things here. On the right hand
python finds that self has no __instance_counter attribute so it will fetch the
value from the class.

However on the left hand, python will create an attribute for self and assign the
value to it. Python will not rebind the class variable.

-- 
Antoon Pardon 

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Question re class variable plewto@gmail.com - 2015-09-29 02:27 -0700
  Re: Question re class variable alister <alister.nospam.ware@ntlworld.com> - 2015-09-29 10:00 +0000
    Re: Question re class variable John Gordon <gordon@panix.com> - 2015-09-29 14:44 +0000
      Re: Question re class variable Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2015-09-29 20:41 -0400
  Re: Question re class variable Antoon Pardon <antoon.pardon@rece.vub.ac.be> - 2015-09-29 12:40 +0200
    Re: Question re class variable Anssi Saari <as@sci.fi> - 2015-09-29 14:17 +0300
      Re: Question re class variable Antoon Pardon <antoon.pardon@rece.vub.ac.be> - 2015-09-29 14:02 +0200
      Re: Question re class variable Steven D'Aprano <steve@pearwood.info> - 2015-09-29 22:06 +1000
      Re: Question re class variable Dennis Lee Bieber <wlfraed@ix.netcom.com> - 2015-09-29 08:21 -0400
  Re: Question re class variable jmp <jeanmichel@sequans.com> - 2015-09-29 13:02 +0200
  Re: Question re class variable jmp <jeanmichel@sequans.com> - 2015-09-29 13:11 +0200

csiph-web