get attribute from a parent class

Christopher T King squirrel at WPI.EDU
Sun Aug 1 22:16:06 EDT 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=A()
>>> b=A()
>>> a.B is b.B
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).




More information about the Python-list mailing list