self.var hmm?

Paul Boddie paul at boddie.org.uk
Tue May 20 17:17:47 EDT 2008


On 20 Mai, 22:58, notnorweg... at yahoo.se wrote:
> class TaskGroup:
>     def __init__(self):
>         self.group = []
>
>     def addTask(self, task):
>         self.group.append(task)
>
> is this wrong? i have a program thats too big to post but should i
> just do group.append in addTask?

No, you have to do self.group.append, since group isn't a local
variable in the addTask method, and I doubt that you'd want addTask to
make changes to any global variable called group, which is what might
happen otherwise - that could be a source of potential problems, so
you need to be aware of that!

> reason is when later doing TaskGroup.group i get None

TaskGroup.group would be referencing a class attribute called group,
which is "shared" by all TaskGroup instances (and the TaskGroup class
itself, of course). What you need to do is to access the instance
attribute called group via each instance, and the self.group notation
does exactly that: self is the reference to a particular instance (in
the addTask method, it's the instance used to call the addTask
method).

You might wonder why Python doesn't know inside a method that group is
a reference to an instance attribute of that name. The reason,
somewhat simplified, is that Python only has assignments to populate
namespaces (such as the contents of an instance), whereas languages
which employ declarations (such as Java) would have you list the
instance attributes up front. In these other languages, the compiler/
interpreter would know that you're executing a method belonging to an
instance of a particular class, and it would also know what names to
expect as references to class and instance attributes.

Anyway, I hope this makes more sense now than it did a few moments
ago. :-)

Paul



More information about the Python-list mailing list