getattr

Peter Hansen peter at engcorp.com
Thu Feb 19 10:27:55 EST 2004


> Srikanth Mandava wrote:
> 
> How can getattr() be used to call a constructor method?

First thing to understand is that "constructor method" is an unclear
concept in Python.  *Old-style* classes don't have constructors, they
have the __init__ initializer method.  When you call it, you don't
get back an instance, since it returns None.

New-style classes have a different approach, and real constructors
are available.  (As I understand it... heck, I haven't even used
them yet! :-)

Are you perhaps thinking of using getattr() to get a reference to the
__init__ method of something, and then calling it?  Why would you
want to use getattr() for that when you can just as for the method
reference directly?  But more to the point: that won't work, since
__init__ is not a constructor.  What you would really be looking for
in this case is the __class__ property, which is callable and which
is probably the closest thing to the "constructor" concept that you
will find here.

If none of this answers the question, try again with more detail
and maybe an example of what you were hoping to do, even if it
doesn't actually work or isn't syntactically correct Python, and
then we'll have a clue what you mean. 

-Peter



More information about the Python-list mailing list