get attribute from a parent class
Christopher T King
squirrel at WPI.EDU
Mon Aug 2 04:16:06 CEST 2004
On Mon, 2 Aug 2004, Steve wrote:
> 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:
>>> a.B is b.B
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
1) Move the definition of B into A.__init__, so a new class referencing
the A instance is created each time:
aself.var = "A's variable"
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:
self.var = "A's variable"
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).
More information about the Python-list