[Tutor] Class Attribute "Overloading?"

wesley chun wescpy at gmail.com
Wed Aug 15 19:14:20 CEST 2007

> Is there any way a reference to a class attribute ([class].[attribute]) be
> treated like a method ([class].[method]())?
>         :
> 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'm not sure exactly what you're asking, but let me say the following:

- you can use the Boolean hasattr() to determine if any object (not
just classes) have an attribute, e.g., hasattr(MyClass, 'anAttr')

- if myInstance is an instance of MyClass, e.g., if the Boolean
isinstance(myInstance, MyClass) returns true, then you can also do
hasattr(myInstance, 'anAttr').  (or 'self' if this code is defined
within a method)

- you can use the Boolean callable() to determine if it can be
"called," or executed like a function, e.g., is hasattr(self,
'anAttr') and callable(self.anAttr): self.anAttr(...)

hasattr(), isinstance(), callable()... 3 useful built-in functions...

hopefully this helps...
-- wesley
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
"Core Python Programming", Prentice Hall, (c)2007,2001

wesley.j.chun :: wescpy-at-gmail.com
python training and technical consulting
cyberweb.consulting : silicon valley, ca

More information about the Tutor mailing list