Page 412 -
P. 412
custom widgets and classes
Q: I don’t get it. What’s this “self” thing again? Q: But why do I need to add “self.” to the start of the
variables?
A: “self” is a variable that refers to the calling object.
Q: The calling object? What does that mean? A: Because then you are changing data inside the current
object referred to by “self.”. You will be working with the object’s
own data, and not with data that belongs to the class.
A: Imagine you create a new method called bleep() in Q:
Not all the variables had “self.” at the beginning. Why
the SoundPanel class. An object called panel can use is that?
the bleep() method as needed, and when it does, it calls the
SoundPanel class. The “self.” bit ensures that the bleep()
method associated with the panel object is called, not some A: If you look at the code, the volume_scale variable
other bleep() method associated with some other object. does not begin with “self.”. That’s because the object does not
need to keep track of the volume_scale variable once the
Q: initializer method has finished creating the object. volume_
So objects don’t actually own their own methods?
scale is a variable that is local to the initializer.
A: In some languages, such as Ruby, they can, but in most
languages, no, objects don’t own their own methods. The methods
all belong to the class that created the object.
The SoundPanel widget is a type of frame. The methods in the class all have a self
variable.
Objects get created by classes.
A class has methods. The self variable points to the object
that called the method.
The methods define the behavior of the By prefixing variables with “self.”, you
object.
can keep each object’s values separate
When an object needs to know what to do, from each other.
it calls a method in the class that created it.
you are here 4 377

