473,408 Members | 1,738 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,408 software developers and data experts.

Obtaining an member function by name

Hi all,

Suppose you have this class:

class foo:
def bar():

Suppose you also have the strings "foo" and "bar". How can you obtain the
function foo.bar()?

Surely somebody knows..

TIA,
g
Nov 22 '05 #1
12 1526
f = getattr(obj,"bar")
f()

guy lateur wrote:
Hi all,

Suppose you have this class:

class foo:
def bar():

Suppose you also have the strings "foo" and "bar". How can you obtain the
function foo.bar()?

Surely somebody knows..

TIA,
g


Nov 22 '05 #2
f = getattr(obj,"bar")
f()

guy lateur wrote:
Hi all,

Suppose you have this class:

class foo:
def bar():

Suppose you also have the strings "foo" and "bar". How can you obtain the
function foo.bar()?

Surely somebody knows..

TIA,
g


Nov 22 '05 #3
guy lateur wrote:
Hi all,

Suppose you have this class:

class foo:
def bar():

Suppose you also have the strings "foo" and "bar". How can you obtain the
function foo.bar()?

Surely somebody knows..


getattr helps. However, your example won't work: it misses either a
staticmethod-declaration, or a self-argument, or a classmethod and
cls-argument. So unless we know if bar shall be an instance.method or
not, it's hard to tell what exactly you want. Because you could want

getattr(getattr(mymodule, "foo"), "bar")

Or

getattr(getattr(mymodule, "foo")(), "bar")

(notice the parentheses)

or

getattr(getattr(locals(), "foo"), "bar")

or

getattr(getattr(globals(), "foo"), "bar")

Diez
Nov 22 '05 #4
guy lateur wrote:
Hi all,

Suppose you have this class:

class foo:
def bar():

Suppose you also have the strings "foo" and "bar". How can you obtain the
function foo.bar()?

Surely somebody knows..


getattr helps. However, your example won't work: it misses either a
staticmethod-declaration, or a self-argument, or a classmethod and
cls-argument. So unless we know if bar shall be an instance.method or
not, it's hard to tell what exactly you want. Because you could want

getattr(getattr(mymodule, "foo"), "bar")

Or

getattr(getattr(mymodule, "foo")(), "bar")

(notice the parentheses)

or

getattr(getattr(locals(), "foo"), "bar")

or

getattr(getattr(globals(), "foo"), "bar")

Diez
Nov 22 '05 #5
On Sat, 19 Nov 2005 14:12:25 GMT, "guy lateur" <gu********************@pandora.be> wrote:
Hi all,

Suppose you have this class:

class foo:
def bar():

Suppose you also have the strings "foo" and "bar". How can you obtain the
function foo.bar()?

Why don't you type these things into an interactive python session
and see what happens? Also, foo.bar will be an unbound method of foo,
not a function per se. You could experiment a little, e.g.,
class foo: ... def bar():
...
File "<stdin>", line 3

^
IndentationError: expected an indented block class foo: ... def bar(): return 'bar is the name' # you could have done this
... foo.bar() Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unbound method bar() must be called with foo instance as first argument (got nothing
instead) foo() <__main__.foo instance at 0x02EF3D8C> foo.bar(foo()) Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: bar() takes no arguments (1 given) class foo: ... def bar(self): return self, 'bar is the name' # you could have done this
... fooinst = foo()
fooinst <__main__.foo instance at 0x02EF756C> foo.bar(fooinst) (<__main__.foo instance at 0x02EF756C>, 'bar is the name') fooinst.bar <bound method foo.bar of <__main__.foo instance at 0x02EF756C>> fooinst.bar() (<__main__.foo instance at 0x02EF756C>, 'bar is the name') foo.bar.im_func <function bar at 0x02EF5764> foo.bar.im_func('first arg') ('first arg', 'bar is the name') fooinst.bar <bound method foo.bar of <__main__.foo instance at 0x02EF756C>> fooinst.bar.im_func <function bar at 0x02EF5764> fooinst.bar.im_func(1234) (1234, 'bar is the name') fooinst.bar() (<__main__.foo instance at 0x02EF756C>, 'bar is the name') foo.bar(333) Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unbound method bar() must be called with foo instance as first argument (got int inst
ance instead) foo.bar(fooinst)

(<__main__.foo instance at 0x02EF756C>, 'bar is the name')

Someone can explain. If you do some of your own work, it will help even the load.
Have you looked at any documentation? Start at http://www.python.org/
and click a few things. There seems to be a beginners guide link under documentation
in the sidebar to the left ;-)

Regards,
Bengt Richter
Nov 22 '05 #6
On Sat, 19 Nov 2005 14:12:25 GMT, "guy lateur" <gu********************@pandora.be> wrote:
Hi all,

Suppose you have this class:

class foo:
def bar():

Suppose you also have the strings "foo" and "bar". How can you obtain the
function foo.bar()?

Why don't you type these things into an interactive python session
and see what happens? Also, foo.bar will be an unbound method of foo,
not a function per se. You could experiment a little, e.g.,
class foo: ... def bar():
...
File "<stdin>", line 3

^
IndentationError: expected an indented block class foo: ... def bar(): return 'bar is the name' # you could have done this
... foo.bar() Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unbound method bar() must be called with foo instance as first argument (got nothing
instead) foo() <__main__.foo instance at 0x02EF3D8C> foo.bar(foo()) Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: bar() takes no arguments (1 given) class foo: ... def bar(self): return self, 'bar is the name' # you could have done this
... fooinst = foo()
fooinst <__main__.foo instance at 0x02EF756C> foo.bar(fooinst) (<__main__.foo instance at 0x02EF756C>, 'bar is the name') fooinst.bar <bound method foo.bar of <__main__.foo instance at 0x02EF756C>> fooinst.bar() (<__main__.foo instance at 0x02EF756C>, 'bar is the name') foo.bar.im_func <function bar at 0x02EF5764> foo.bar.im_func('first arg') ('first arg', 'bar is the name') fooinst.bar <bound method foo.bar of <__main__.foo instance at 0x02EF756C>> fooinst.bar.im_func <function bar at 0x02EF5764> fooinst.bar.im_func(1234) (1234, 'bar is the name') fooinst.bar() (<__main__.foo instance at 0x02EF756C>, 'bar is the name') foo.bar(333) Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unbound method bar() must be called with foo instance as first argument (got int inst
ance instead) foo.bar(fooinst)

(<__main__.foo instance at 0x02EF756C>, 'bar is the name')

Someone can explain. If you do some of your own work, it will help even the load.
Have you looked at any documentation? Start at http://www.python.org/
and click a few things. There seems to be a beginners guide link under documentation
in the sidebar to the left ;-)

Regards,
Bengt Richter
Nov 22 '05 #7
guy lateur wrote:
Hi all,

Suppose you have this class:

class foo:
def bar():

Suppose you also have the strings "foo" and "bar". How can you obtain the
function foo.bar()?

Surely somebody knows..

TIA,
g

Would that do?
class foo: @staticmethod
def bar():
pass

foo.bar <function bar at 0x00B445F0>

Nov 22 '05 #8
guy lateur wrote:
Hi all,

Suppose you have this class:

class foo:
def bar():

Suppose you also have the strings "foo" and "bar". How can you obtain the
function foo.bar()?

Surely somebody knows..

TIA,
g

Would that do?
class foo: @staticmethod
def bar():
pass

foo.bar <function bar at 0x00B445F0>

Nov 22 '05 #9
On Sat, 19 Nov 2005 14:12:25 GMT, "guy lateur" <gu********************@pandora.be> wrote:
Hi all,

Suppose you have this class:

class foo:
def bar():

Suppose you also have the strings "foo" and "bar". How can you obtain the
function foo.bar()?

Surely somebody knows..

Sorry, clean forgot about the strings.
class foo: ... def bar(self): return self, 'bar is the name'
... # The definition is at global scope, so 'foo' will show up ... # in the globals() directory, which we can access with appended ['foo']
... globals()['foo'] <class __main__.foo at 0x02EE9C2C> #if you want the 'bar' attribute using the string ... getattr(globals()['foo'], 'bar')
<unbound method foo.bar> foo.bar

<unbound method foo.bar>

Note that getting an attribute does some "binding" magic if the
attribute has certain qualitites. In this case the bar function
is associated with the foo class to become an "unbound method"

Nit: usual convention is to spell class names with leading upper case.
Then you can e.g. use the lower case same name for an instance of the
class without confusions. Nit2: using new-style classes, which derive
from object (or also other bases, but at least object or type) is now
recommended, so you get the full-fledged attribute machinery that supports
much of the latest magic. So write the above more like

class Foo(object):
def bar(self): return self, 'bar is the name'

Regards,
Bengt Richter
Nov 22 '05 #10
On Sat, 19 Nov 2005 14:12:25 GMT, "guy lateur" <gu********************@pandora.be> wrote:
Hi all,

Suppose you have this class:

class foo:
def bar():

Suppose you also have the strings "foo" and "bar". How can you obtain the
function foo.bar()?

Surely somebody knows..

Sorry, clean forgot about the strings.
class foo: ... def bar(self): return self, 'bar is the name'
... # The definition is at global scope, so 'foo' will show up ... # in the globals() directory, which we can access with appended ['foo']
... globals()['foo'] <class __main__.foo at 0x02EE9C2C> #if you want the 'bar' attribute using the string ... getattr(globals()['foo'], 'bar')
<unbound method foo.bar> foo.bar

<unbound method foo.bar>

Note that getting an attribute does some "binding" magic if the
attribute has certain qualitites. In this case the bar function
is associated with the foo class to become an "unbound method"

Nit: usual convention is to spell class names with leading upper case.
Then you can e.g. use the lower case same name for an instance of the
class without confusions. Nit2: using new-style classes, which derive
from object (or also other bases, but at least object or type) is now
recommended, so you get the full-fledged attribute machinery that supports
much of the latest magic. So write the above more like

class Foo(object):
def bar(self): return self, 'bar is the name'

Regards,
Bengt Richter
Nov 22 '05 #11
Thanks for the feedback, people.

I actually only need the "bar" part (instance methods). I added the "foo"
part to generalize the question without really thinking it through first.
Still, it has gotten me more information than I ever imagined. So thanks
again.

g
Nov 22 '05 #12
Thanks for the feedback, people.

I actually only need the "bar" part (instance methods). I added the "foo"
part to generalize the question without really thinking it through first.
Still, it has gotten me more information than I ever imagined. So thanks
again.

g
Nov 22 '05 #13

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
by: Alexander Stippler | last post by:
Can someone explain the following construct to me: What is not clear to me is what the argument to foo is. A pointer to a member? template <class U> static char foo(void (U::*)(void)); ...
15
by: Peter Olcott | last post by:
Does anyone know how to do this?
6
by: Bill Rubin | last post by:
The following code snippet shows that VC++ 7.1 correctly compiles a static member function invocation from an Unrelated class, since this static member function is public. I expected to compile the...
2
by: amirmira | last post by:
Hi, I have an application where I monitor the status of a machine using it's IP address. I would like to log an error when the machine goes down - but I want to add the name of the machine along...
0
by: guy lateur | last post by:
Hi all, Suppose you have this class: class foo: def bar(): Suppose you also have the strings "foo" and "bar". How can you obtain the function foo.bar()?
11
by: seannakasone | last post by:
Is there a way to get the callstack level in c++? for example, take the following code: void call3() { //callstack level would be 3 } void call2() { //callstack level would be 2 call3();
11
by: John Nagle | last post by:
The Python SSL object offers two methods from obtaining the info from an SSL certificate, "server()" and "issuer()". The actual values in the certificate are a series of name/value pairs in ASN.1...
9
by: psujkov | last post by:
Hi everybody, int f(int a, int b) { return a + b; }; is it possible to obtain this function signature - int (int, int) in this case - for use in boost::function_traits ? e.g. std::cout << "f's...
1
by: psujkov | last post by:
Hi everybody, in addition to my previous question, first of all this : template<typename F> void foo(const F& f) { std::cout << boost::function_traits<F>::arity << std::endl; }
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.