Vincent Gulinao wrote:
> Sorry, I just started experimenting on Python classes...
>
> Is there any way a reference to a class attribute ([class].[attribute])
> be treated like a method ([class].[method]())?
>
> I have a class with DB component. Some of its attributes are derived
> from DB and I find it impractical to derive all at once upon __init__.
>
> Of course we can use dictionary-like syntax ([class]["[attribute]"]) and
> use __getitem__, checking for existence and None of the attribute before
> deriving the value from the DB. But I think [class].[attribute] is more
> conventional (Is it?). Or someone suggest a more Pythonic way.
I think you are looking for either __getattr__() or properties.
__getattr__() lets you intercept access to atttributes that are not
found via the usual attribute lookup. It is useful for delegation which
I think is what you are trying to do. e.g.
class Proxy(object):
def __init__(self, delegate):
self.delegate = delegate
def __getattr__(self, attr):
return getattr(self.delegate, attr)
then with
p = Proxy(realObject)
p.x becomes p.delegate.x i.e. realObject.x
http://docs.python.org/ref/attribute-access.html
Properties OTOH let you customize access to a particular attribute so
p.x becomes a method call.
http://www.python.org/download/releases/2.2/descrintro/#property
Kent
_______________________________________________
Tutor maillist - [email protected]
http://mail.python.org/mailman/listinfo/tutor