Confounded by Python objects

Fredrik Lundh fredrik at pythonware.com
Thu Jul 24 05:59:29 EDT 2008


boblatest at googlemail.com wrote:

> take a look at the code snippet below. What I want to do is initialize
> two separate Channel objects and put some data in them. However,
> although two different objects are in fact created (as can be seen
> from the different names they spit out with the "diag()" method), the
> data in the "sample" member is the same although I stick different
> values in.

that's because you only have one sample object -- the one owned by
the class object.

since you're modifying that object in place (via the append method),
your changes will be shared by all instances.  python never copies 
attributes when it creates an instance; if you want a fresh object,
you have to create it yourself.

> class Channel:

tip: if you're not 100% sure why you would want to put an attribute
on the class level, don't do it.  instead, just create all attributes
inside the __init__ method:

>     def __init__(self, name):
>         self.name = name
           self.sample = [] # create fresh container for instance

>     def append(self, time, value):
>         self.sample.append((time, value))
>         self.diag()
> 
>     def diag(self):
>         print (self.name, self.sample)

hope this helps!

</F>




More information about the Python-list mailing list