<< Chapter < Page | Chapter >> Page > |
Listing 4 . Object can modify itself at runtime. |
---|
class TestClass(object):
def addInstanceVar(self,data):self.iVar = data |
I am presenting and explaining this program for a couple of different reasons:
The other difference between the two programs is shown in Listing 5 . Instead of accessing the object directly to add the new instance variable, as was done in Listing 2 , the code in Listing 5 calls the method named addInstanceVar on the object to cause the new instance variable to be added.
Listing 5 . Add an instance variable to one object and display it. |
---|
print("Add an instance variable to one object and display it")
ref01.addInstanceVar(1234)print(ref01.iVar) |
As mentioned earlier, the end result is the same as you will see if you examine the output from the program shown in Listing 11 .
Once again, I recommend that you create a visualization for the code in Listing 10 and step through the program one instruction at a time. As you do that, pay attention tothe movements of the red and green arrows on the left, the diagram on the right, and the printed material at the bottom. That should help you to betterunderstand how a Python object can modify itself at runtime.
You learned in the previous program that a method belonging to an object can add an instance variable to an object at runtime.
You also learned in an earlier module that if your class contains a method named __init__ , that method will be executed automatically in conjunction with the instantiation of the object. As I understand it, that isprobably the last thing that happens before the new object's reference is returned to be saved for later use.
A complete listing of a program that I will use to discuss the __init__ method is shown in Listing 11 . The output produced by that program is shown in Figure 7 . As usual, I will explain the program in fragments.
Listing 6 shows the definition of a class named TestClass that contains a method named __init__ in addition to a method named addInstanceVar as in the previous program.
Listing 6 . A class with an __init__ method. |
---|
class TestClass(object):
def __init__(self,data):self.iVar01 = datadef addInstanceVar(self,data):
self.iVar02 = data |
When either of the methods shown in Listing 6 are executed, a new instance variable will be added to the object and initialized with an incoming datavalue. Since the method named __init__ is always executed automatically in conjunction with the instantiation of an object, the initial state of theobject will include an instance variable named iVar01 .
The code in Listing 7 instantiates and prints two new objects of the class named TestClass . You can view the output produced by the code in Listing 7 in Figure 7 . There probably won't be any surprises there.
Notification Switch
Would you like to follow the 'Itse 1359 introduction to scripting languages: python' conversation and receive update notifications?