I am trying to learn OO Python, and I have a doubt regarding the scope of object attributes once it has been instantiated. So, I decided to write a very simple program:
class Struct:
def __init__(self):
self.resadd=[]
self.ressub=[]
self.resmul=[]
class MathStruct:
def mathss(self,x,y):
add=x+y
sub=x-y
mul=x*y
resstruct.resadd.append(add)
resstruct.ressub.append(sub)
resstruct.resmul.append(mul)
if __name__=='__main__':
resstruct=Struct()
for i in range(10,20):
mathsstuff=MathStruct()
mathsstuff.mathss(i,5)
print len(resstruct.resadd),resstruct.resadd
print len(resstruct.ressub),resstruct.ressub
print len(resstruct.resmul),resstruct.resmul
As you can see, the program is quite straightforward – but, here is my question – I instantiate the “result” object using:
resstruct=Struct()
and then use the resstruct.resadd, resstruct.ressub and resstruct.resmul attributes within the “mathss” function. Is this legal(I get the right answer!)? Does this mean that the object attributes are available even within other functions?
Normally, I would return values from the function and then append it to the object attribute, but I was (pleasantly) surprised to see that I can directly modify the object attribute within another function.
..In a nutshell, my question is what is the scope of the object attributes once it is instantiated? Sorry if this is a 101 question.
The line
restruct = Struct()occurs at the module top level, outside any function or class, so it creates an object in the module global namespace. This namespace is, as the term implies, global to the module, and can be accessed from all functions. If you had donerestruct = Struct()inside a function, it wouldn’t be global and would disappear when the function finished.In other words, if you had created it in a function scope, the object’s lifetime would be limited to that scope. But you created it in global scope, so it lives forever. (An object’s attributes have no scope of their own as such; they are inside that object’s own instance namespace and are accessible only via the object. You can access
obj.attrwhenever you can accessobj.)(Note, though, that assigning to global variables from inside a function requires a
globalstatement. You are able to accessrestructbecause you only read the value of the variable and mutate that object with methods. If you tried to assign torestructwithin a function, you would be creating a new local variable shadowing the global one.)