Get bound method by name

J

Johannes Bauer

Hello group,

I'm looking for a Python function but have forgotten it's name.
Essentially what I want is:

class Foo():
def bar(self):
pass

x = Foo()
y = x.MAGIC("bar")
print(y)
<bound method Foo.bar of <__main__.Foo instance at 0xb7e11fcc>>

So the question is: How is the magic function called which returns me
the bound method of a class instance by its name? I know there was a way
but just can't remember...

Thanks in advance,
Kind regards,
Johannes
 
J

John Machin

Hello group,

I'm looking for a Python function but have forgotten it's name.
Essentially what I want is:

class Foo():
        def bar(self):
                pass

x = Foo()
y = x.MAGIC("bar")
print(y)
<bound method Foo.bar of <__main__.Foo instance at 0xb7e11fcc>>

So the question is: How is the magic function called which returns me
the bound method of a class instance by its name? I know there was a way
but just can't remember...

getattr(x, "bar")
 
C

Chris Rebert

Hello group,

I'm looking for a Python function but have forgotten it's name.
Essentially what I want is:

class Foo():
       def bar(self):
               pass

x = Foo()
y = x.MAGIC("bar")

getattr() is the function you seek.

y = getattr(x, "bar")
print(y)
<bound method Foo.bar of <__main__.Foo instance at 0xb7e11fcc>>

Cheers,
Chris
 
G

Graham Breed

Johannes said:
Hello group,

I'm looking for a Python function but have forgotten it's name.
Essentially what I want is:

class Foo():
def bar(self):
pass

x = Foo()
y = x.MAGIC("bar")
print(y)
<bound method Foo.bar of <__main__.Foo instance at 0xb7e11fcc>>

So the question is: How is the magic function called which returns me
the bound method of a class instance by its name? I know there was a way
but just can't remember...

y = getattr(x, "bar")
 
C

Chris Rebert

Or, as a method call (which was requested):

The OP was a bit inconsistent. He only used the word "function", but
his pseudocode used a method.
Either way, one shouldn't normally use magic methods directly.

Cheers,
Chris
 

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

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,066
Latest member
VytoKetoReviews

Latest Threads

Top