inner classes in python as inner classes in Java

Carlo v. Dango oest at soetu.eu
Wed Oct 15 11:52:48 EDT 2003


Inner classes in Python is merely hidding of structure rather than 
providing a scope as in Java. eg. this program fails in the print-line..


class A(object):
	def __init__(self):
		self.name = "hans"
		
	class B(object):
		def foo(self):
			print "my name is " , self.name
a = A()
b = a.B()
b.foo()


to remedy this, I thought of having an "outer" attribute which was 
accessed when the class itself could not find a given property. However, I 
think the following definition is problematic as it bites itself. in the 
init method i introduce the "outer" field.. however, at this point the 
__getattr__ is called which makes me look in the outer scope.. which was 
not the intention. How to do a proper implementation?


class A(object):
	def __init__(self):
		self.name = "hans"
		
	class B(object):
		def __init__(self, outer=None):
			self.outer = outer
			
		def foo(self):
			print "my name is " , self.name

		def __getattr__(self, name):
			if self.outer != None:
				return self.outer.getattr(name)
			else: raise Error("attribute ", name, " not found!")

		def __setattr__(self, name, value):			
			if self.outer != None:
				self.outer.setattr(name, value)
			else: raise Error("attribute ", name, " not found!")

a = A()
b = a.B(a)
b.foo()




Carlo...

-- 
Using M2, Opera's revolutionary e-mail client: http://www.opera.com/m2/




More information about the Python-list mailing list