Confounded by Python objects
alex23
wuwei23 at gmail.com
Thu Jul 24 06:03:09 EDT 2008
On Jul 24, 7:45 pm, "boblat... at googlemail.com"
<boblat... at googlemail.com> wrote:
> class Channel:
> name = ''
> sample = []
>
> def __init__(self, name):
> self.name = name
>
> def append(self, time, value):
> self.sample.append((time, value))
> self.diag()
>
> def diag(self):
> print (self.name, self.sample)
Okay, the problem is you're appending to a _class_ attribute, not to
an instance attribute.
If you change your class definition to this, it should work:
class Channel:
def __init__(self, name):
self.name = name
self.sample = []
That will provide each instance with its own version of the sample
attribute.
The 'self.name = name' in the __init__ for your original code binds a
new attribute to the instance, whereas 'self.sample.append(...' in the
class's append was appending to the class attribute instead.
Hope this helps.
- alex23
More information about the Python-list
mailing list