[Tutor] attribute of built-in type

Kent Johnson kent37 at tds.net
Tue Dec 2 04:03:40 CET 2008


Here is an idea that might help - you do have some control over
assignment to attributes of an object. If you stored your objects in
another object you could assign __name__ attributes automatically. For
example:

class Container(object):
	def __setattr__(self, name, value):
	   if not hasattr(value, '__name__'):
	      try:
	         value.__name__ = name
	      except:
	         pass
	   object.__setattr__(self, name, value)

class Item(object):
   pass

c = Container()
c.s = 'string'
c.i = Item()

print c.i.__name__   # i
print c.s.__name__   # AttributeError, can't add __name__ attribute to string

Kent


More information about the Tutor mailing list