extend getattr()

Jared Grubb jared.grubb at gmail.com
Fri Jun 27 09:41:41 CEST 2008


You could overload __getattr__ (might have to play around a bit to make sure
any possible AttributeError's look right, but the basic idea is here)
class A(object):
  # ...
  def __getattr__(self, name):
      try:
        return object.__getattribute__(self, name)
      except AttributeError:
        if '.' in name:
          attrs = name.split('.')
          first = object.__getattribute__(self, attrs[0])
          return getattr(first, '.'.join(attrs[1:]))
        raise

>>> a = A()
>>> a.b = A()
>>> a.b.c = A()
>>> a.b.c.d = A()
>>> getattr(a, 'b.c.d')
<__main__.A object at 0x67f50>




On 26 Jun 2008, at 04:06, Rotlaus wrote:

Hello,

lets assume i have some classes:

class A(object):
   def __init__(self):
       b = B()

class B(object):
   def __init__(self):
       c = C()

class C(object):
   def __init__(self):
       pass

and now i wanna do something like this:

a=A()
c=getattr(a, 'b.c')

I know this doesn't work, but what can i do to get this or a similar
functionality to get it work for this sample and for even more nested
classes?

Kind regards,

Andre
--
http://mail.python.org/mailman/listinfo/python-list
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20080627/718e19e3/attachment.html>


More information about the Python-list mailing list