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.