getattr

S

Srikanth Mandava

Hi,

How can getattr() be used to call a constructor method?

Thanks
Srikanth
 
P

Peter Hansen

Srikanth said:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,767
Messages
2,569,572
Members
45,046
Latest member
Gavizuho

Latest Threads

Top