November 11th, 2012, 04:08 PM
Scope of Class Variables and Methods
I have a question about class variables and scope in Python.
Here is the code:
a = "this is b, the b of Super without self"
self.b="this is b, the self.b of Super"
c = "this is c, of sub, without self"
self.d = "this is d, self.d of Sub"
abcd = Sub()
Why wouldn't I be able to type abcd.a and get the value of a? I must be misunderstanding something--isn't the point of the __init__ function in the superclass to initialize variables in the subclasses, so that they can be used without having to define them in every class using self?
November 11th, 2012, 07:57 PM
self is the name of the variable assigned the new Super object
a = 'THIS VARIABLE IS LOCAL TO THE __init__ FUNCTION' # a is inaccessible after the function finishes.
# (or at least it's hard to find)
self.b='THIS ASSIGNS AN ATTRIBUTE OF A Super OBJECT'
self is common but not reserved nor special.
Any variable name will do.
(At least you'll have trouble finding an exception to that statement.)
c = 'THIS VARIABLE IS LOCAL TO THE __init__ FUNCTION'
x.d = 'THIS ASSIGNS AN ATTRIBUTE OF A Sub OBJECT'
abcd = Sub()
print('abcd.b is %s'%abcd.b)
print('abcd.d is %s'%abcd.d)
[/code] are essential for python code and Makefiles!
November 12th, 2012, 12:40 PM
Ahh-- this makes sense now. Thank you for the help!