[Tutor] defining __init__
Danny Yoo
dyoo at hkn.eecs.berkeley.edu
Fri Jan 13 21:33:15 CET 2006
On Fri, 13 Jan 2006, S. D. Rose wrote:
> One thing about classes that really tripped me up when I first started
> using classes was 'self' before the variable. When you have '
> self.variable ' that is a variable that can be referenced by the parent.
> If there's no 'self' before the variable, you can not.
>
> For instance, if you have a routine:
>
> class Dog:
> def __init__(self, color):
> self.color = color
> age = 16
Hi Dave,
'age' here is a local variable, just like any other local variable that
we've used in other function definitions.
> It will error out, because you can not reference age without pre-pending
> a 'self.'
There might be some confusion here --- you mention parents and children,
when there aren't any involved --- so let's talk about this in more
detail.
The key observation we need to make is that the first assignment:
> self.color = color
makes a state change to the class instance.
But:
> age = 16
makes an assignment to a local variable 'age', and that variable has no
connection to the state of the Dog.
Let's get away, for a moment, from class stuff, and let's take a quicky
example with just functions:
###
def initializeThing(thing):
thing['color'] = 'blue'
age = 42
d = {}
initializeThing(d)
print d
###
Do we expect to see 'age' in the 'd' dictionary?
If you have more questions, please feel free to ask.
More information about the Tutor
mailing list