[Tutor] Class Attribute "Overloading?"
Noufal Ibrahim
noufal at airtelbroadband.in
Wed Aug 15 20:58:06 CEST 2007
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.
>
Do you simply want to dynamically create class attributes? If so, you
can use setattr. Something like this
class foo(object):
def __init__(self, *args):
for i in args:
setattr(self,i,"Hello=%s"%i)
x=foo("a","b","c")
print x.a,x.b,x.c
will print
Hello=a Hello=b Hello=c
--
~noufal
More information about the Tutor
mailing list