#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    2
    Rep Power
    0

    Scope of Class Variables and Methods


    I have a question about class variables and scope in Python.

    Here is the code:
    ######
    class Super:
    def __init__(self):
    a = "this is b, the b of Super without self"
    self.b="this is b, the self.b of Super"

    class Sub(Super):
    def __init__(self):
    Super.__init__(self)
    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?
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,995
    Rep Power
    481
    Code:
    class Super:
    
        def __init__(self):
            '''
                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'
    
    class Sub(Super):
    
        def __init__(x):
            '''
                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.)
            '''
            Super.__init__(x)
            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]Code tags[/code] are essential for python code and Makefiles!
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2012
    Posts
    2
    Rep Power
    0
    Ahh-- this makes sense now. Thank you for the help!

IMN logo majestic logo threadwatch logo seochat tools logo