get attribute from a parent class

S

Steve

Hi,

I have a nested class declaration such as:

class A:
def __init__(self):
self.var = "A's variable"
# end def

class B:
def __init__(self):
self.var2 = "B's variable"
# end def
# end class B
# end class A


What I want to do is to be able to get class A's 'var' variable from the
nested class B. For example, I want to be able to do something like:
print "I can see you %s" % a.var


but... I don't want to make 'var' a class variable. I want it to be an
instance variable but still be viewable by the inner class B. Is this
possible? Any suggestions? Thanks

Steve
 
C

Christopher T King

What I want to do is to be able to get class A's 'var' variable from the
nested class B. For example, I want to be able to do something like:
print "I can see you %s" % a.var


but... I don't want to make 'var' a class variable. I want it to be an
instance variable but still be viewable by the inner class B. Is this
possible? Any suggestions? Thanks

There is no way to do this without changing your code slightly, the reason
being that class B is a static definition, and refers to the same object
in every instantiation of A:
True

To get the effect you want, you must somehow get a reference to an A
object to the definition of the B object. There are two basic ways to do
this:

1) Move the definition of B into A.__init__, so a new class referencing
the A instance is created each time:

class A:
def __init__(aself):
aself.var = "A's variable"

class B:
def __init__(bself):
bself.var2 = "B's variable"
bself.parent = self
aself.B = B

2) Allow an instance of A to be passed in the constructor to B:

class A:
def __init__(self):
self.var = "A's variable"

class B:
def __init__(self,parent):
self.var2 = "B's variable"
self.parent = parent

Of the two, I prefer the latter, since it is much faster and the code is
cleaner. The only downside is the redundancy of creating B (you have to
call a.B(a) instead of a.B()).

There is probably a way to get the usage of the former with the efficiency
of the latter by using metaclasses, but I don't know how to do it (mostly
because I don't like metaclasses very much).
 
L

Larry Bates

I normally do something like this:

class A:
def __init__(self, parent):
self.parent=parent
#
# Access parent's variables by using
# self.parent.<attribute>.
#
self.var = parent.var2
t1=self.parent.var1
t2=self.parent.var2
return

class B:
def __init__(self):
self.var1=0
self.var2=1
self.classA=A(self)
#
# Access classA's attributes by using
# self.classA.<attribute>
#
t1=A.var
return

HTH,
Larry Bates
Syscon, Inc.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,202
Messages
2,571,057
Members
47,666
Latest member
selsetu

Latest Threads

Top