problems creating and adding class instances to a list:

Chris Rebert clp2 at rebertia.com
Mon Apr 19 17:38:55 EDT 2010


On Mon, Apr 19, 2010 at 2:29 PM, Xavier Ho <contact at xavierho.com> wrote:
> On Tue, Apr 20, 2010 at 7:21 AM, Robert Somerville
> <rsomerville at sjgeophysics.com> wrote:
>>
>> class ctest():
>>   x = int
>>   y = [1,2,3]
>
> Variables defined directly under the class are known as "static variables"
> in many other languages. Here in Python it's called a class variable, but
> they're still the same concept.
>
> What you want is "instance variables", which are not shared by the class
> instances, but different depending on each instance instead. That said,
>
> class ctest():
>     def __init__(self):
>         self.x = int

Additionally, `self.x = int` might not do what you thought it does. It
does *not* create a new instance variable of type 'int'. Instead, it
literally assigns to a new instance variable x the *function*† that
converts values into integers.

Cheers,
Chris
--
† This isn't entirely accurate; I'm oversimplifying for ease of understanding.
http://blog.rebertia.com



More information about the Python-list mailing list