...

View Full Version : Python: Scope of class variables and methods.



Tay
11-11-2012, 09:43 PM
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?

BluePanther
11-12-2012, 04:43 PM
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?

Reposted for you, using the code tags to preserve formatting - important in python

BluePanther
11-12-2012, 04:56 PM
Right. Had a look, and there's a very valid reason why you won't be able to get .a, but retrieve .b.

The self keyword passes the class object into the initiation function. So, to assign a property to the class you need to use self.property name.

In other words, using a on it's own keeps it in the function scope, but using self.a assigns a property to the class object.

Tay
11-12-2012, 06:40 PM
Thanks so much for the help. I knew there were some simple rules that I wasn't quite understanding. Somehow I couldn't get that from searching.

BluePanther
11-12-2012, 07:35 PM
Thanks so much for the help. I knew there were some simple rules that I wasn't quite understanding. Somehow I couldn't get that from searching.

Not a problem :). Scope is a tricky subject when you're learning, sometimes.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum