Simple Acquisition, without proxies nor circular references

Just van Rossum just at letterror.com
Wed Mar 29 08:54:59 EST 2000


Not sure if this is a) a new approach and b) whether it is at all useful,
but it occurred to me the there is a simple way to do attribute 
acquisition, without the overhead of proxies, while still not creating
circular references. The trick is to use a custom attribute dict, and
reference that dict from containing objects instead of the objects
itself. I've pasted a small example below. The naming convention
used is: any attribute name starting with an underscore will *not*
be acquired by children, all others are.

Comments anyone?

Just



class Node:
	
	__instancecount__ = 0  # for testing only
	
	def __init__(self, container=None):
		if container is None:
			self.__names__ = ({},)
		else:
			self.__names__ = ({},) + container.__names__
		self._children = []
		Node.__instancecount__ = Node.__instancecount__ + 1
	
	def add(self, node):
		self._children.append(node)
	
	def __setattr__(self, attr, value):
		if attr[0] == "_":
			self.__dict__[attr] = value
		else:
			self.__names__[0][attr] = value
	
	def __getattr__(self, attr):
		for dict in self.__names__:
			if dict.has_key(attr):
				return dict[attr]
		raise AttributeError, attr
	
	def __del__(self):
		Node.__instancecount__ = Node.__instancecount__ - 1


root = Node()

n1 = Node(root)
n2 = Node(root)
root.add(n1)
root.add(n2)

n3 = Node(n2)
n2.add(n3)

root.color = "Red"
print "should be Red:", n1.color
print "should be Red:", n2.color
print "should be Red:", n3.color
root.color = "Blue"
n2.color = "Yellow"
print "should be Blue:", n1.color
print "should be Yellow:", n2.color
print "should be Yellow:", n3.color

del root, n1, n2, n3

if Node.__instancecount__:
	print "There are %s Nodes still alive" % Node.__instancecount__
else:
	print "No Nodes left."







More information about the Python-list mailing list