Obtaining an member function by name

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • guy lateur

    #1

    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


  • bonono@gmail.com

    #2
    Re: Obtaining an member function by name

    f = getattr(obj,"ba r")
    f()

    guy lateur wrote:[color=blue]
    > 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[/color]

    Comment

    • bonono@gmail.com

      #3
      Re: Obtaining an member function by name

      f = getattr(obj,"ba r")
      f()

      guy lateur wrote:[color=blue]
      > 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[/color]

      Comment

      • Diez B. Roggisch

        #4
        Re: Obtaining an member function by name

        guy lateur wrote:[color=blue]
        > 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..[/color]

        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

        Comment

        • Diez B. Roggisch

          #5
          Re: Obtaining an member function by name

          guy lateur wrote:[color=blue]
          > 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..[/color]

          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

          Comment

          • Bengt Richter

            #6
            Re: Obtaining an member function by name

            On Sat, 19 Nov 2005 14:12:25 GMT, "guy lateur" <guy.lateurNNOO SSPPAAMM@pandor a.be> wrote:
            [color=blue]
            >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()?[/color]
            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.,
            [color=blue][color=green][color=darkred]
            >>> class foo:[/color][/color][/color]
            ... def bar():
            ...
            File "<stdin>", line 3

            ^
            IndentationErro r: expected an indented block[color=blue][color=green][color=darkred]
            >>> class foo:[/color][/color][/color]
            ... def bar(): return 'bar is the name' # you could have done this
            ...[color=blue][color=green][color=darkred]
            >>> foo.bar()[/color][/color][/color]
            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)[color=blue][color=green][color=darkred]
            >>> foo()[/color][/color][/color]
            <__main__.foo instance at 0x02EF3D8C>[color=blue][color=green][color=darkred]
            >>> foo.bar(foo())[/color][/color][/color]
            Traceback (most recent call last):
            File "<stdin>", line 1, in ?
            TypeError: bar() takes no arguments (1 given)[color=blue][color=green][color=darkred]
            >>> class foo:[/color][/color][/color]
            ... def bar(self): return self, 'bar is the name' # you could have done this
            ...[color=blue][color=green][color=darkred]
            >>> fooinst = foo()
            >>> fooinst[/color][/color][/color]
            <__main__.foo instance at 0x02EF756C>[color=blue][color=green][color=darkred]
            >>> foo.bar(fooinst )[/color][/color][/color]
            (<__main__.foo instance at 0x02EF756C>, 'bar is the name')[color=blue][color=green][color=darkred]
            >>> fooinst.bar[/color][/color][/color]
            <bound method foo.bar of <__main__.foo instance at 0x02EF756C>>[color=blue][color=green][color=darkred]
            >>> fooinst.bar()[/color][/color][/color]
            (<__main__.foo instance at 0x02EF756C>, 'bar is the name')[color=blue][color=green][color=darkred]
            >>> foo.bar.im_func[/color][/color][/color]
            <function bar at 0x02EF5764>[color=blue][color=green][color=darkred]
            >>> foo.bar.im_func ('first arg')[/color][/color][/color]
            ('first arg', 'bar is the name')[color=blue][color=green][color=darkred]
            >>> fooinst.bar[/color][/color][/color]
            <bound method foo.bar of <__main__.foo instance at 0x02EF756C>>[color=blue][color=green][color=darkred]
            >>> fooinst.bar.im_ func[/color][/color][/color]
            <function bar at 0x02EF5764>[color=blue][color=green][color=darkred]
            >>> fooinst.bar.im_ func(1234)[/color][/color][/color]
            (1234, 'bar is the name')[color=blue][color=green][color=darkred]
            >>> fooinst.bar()[/color][/color][/color]
            (<__main__.foo instance at 0x02EF756C>, 'bar is the name')[color=blue][color=green][color=darkred]
            >>> foo.bar(333)[/color][/color][/color]
            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)[color=blue][color=green][color=darkred]
            >>> foo.bar(fooinst )[/color][/color][/color]
            (<__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

            Comment

            • Bengt Richter

              #7
              Re: Obtaining an member function by name

              On Sat, 19 Nov 2005 14:12:25 GMT, "guy lateur" <guy.lateurNNOO SSPPAAMM@pandor a.be> wrote:
              [color=blue]
              >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()?[/color]
              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.,
              [color=blue][color=green][color=darkred]
              >>> class foo:[/color][/color][/color]
              ... def bar():
              ...
              File "<stdin>", line 3

              ^
              IndentationErro r: expected an indented block[color=blue][color=green][color=darkred]
              >>> class foo:[/color][/color][/color]
              ... def bar(): return 'bar is the name' # you could have done this
              ...[color=blue][color=green][color=darkred]
              >>> foo.bar()[/color][/color][/color]
              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)[color=blue][color=green][color=darkred]
              >>> foo()[/color][/color][/color]
              <__main__.foo instance at 0x02EF3D8C>[color=blue][color=green][color=darkred]
              >>> foo.bar(foo())[/color][/color][/color]
              Traceback (most recent call last):
              File "<stdin>", line 1, in ?
              TypeError: bar() takes no arguments (1 given)[color=blue][color=green][color=darkred]
              >>> class foo:[/color][/color][/color]
              ... def bar(self): return self, 'bar is the name' # you could have done this
              ...[color=blue][color=green][color=darkred]
              >>> fooinst = foo()
              >>> fooinst[/color][/color][/color]
              <__main__.foo instance at 0x02EF756C>[color=blue][color=green][color=darkred]
              >>> foo.bar(fooinst )[/color][/color][/color]
              (<__main__.foo instance at 0x02EF756C>, 'bar is the name')[color=blue][color=green][color=darkred]
              >>> fooinst.bar[/color][/color][/color]
              <bound method foo.bar of <__main__.foo instance at 0x02EF756C>>[color=blue][color=green][color=darkred]
              >>> fooinst.bar()[/color][/color][/color]
              (<__main__.foo instance at 0x02EF756C>, 'bar is the name')[color=blue][color=green][color=darkred]
              >>> foo.bar.im_func[/color][/color][/color]
              <function bar at 0x02EF5764>[color=blue][color=green][color=darkred]
              >>> foo.bar.im_func ('first arg')[/color][/color][/color]
              ('first arg', 'bar is the name')[color=blue][color=green][color=darkred]
              >>> fooinst.bar[/color][/color][/color]
              <bound method foo.bar of <__main__.foo instance at 0x02EF756C>>[color=blue][color=green][color=darkred]
              >>> fooinst.bar.im_ func[/color][/color][/color]
              <function bar at 0x02EF5764>[color=blue][color=green][color=darkred]
              >>> fooinst.bar.im_ func(1234)[/color][/color][/color]
              (1234, 'bar is the name')[color=blue][color=green][color=darkred]
              >>> fooinst.bar()[/color][/color][/color]
              (<__main__.foo instance at 0x02EF756C>, 'bar is the name')[color=blue][color=green][color=darkred]
              >>> foo.bar(333)[/color][/color][/color]
              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)[color=blue][color=green][color=darkred]
              >>> foo.bar(fooinst )[/color][/color][/color]
              (<__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

              Comment

              • EuGeNe

                #8
                Re: Obtaining an member function by name

                guy lateur wrote:[color=blue]
                > 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
                >
                >[/color]


                Would that do?
                [color=blue][color=green][color=darkred]
                >>> class foo:[/color][/color][/color]
                @staticmethod
                def bar():
                pass

                [color=blue][color=green][color=darkred]
                >>> foo.bar[/color][/color][/color]
                <function bar at 0x00B445F0>[color=blue][color=green][color=darkred]
                >>>[/color][/color][/color]

                Comment

                • EuGeNe

                  #9
                  Re: Obtaining an member function by name

                  guy lateur wrote:[color=blue]
                  > 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
                  >
                  >[/color]


                  Would that do?
                  [color=blue][color=green][color=darkred]
                  >>> class foo:[/color][/color][/color]
                  @staticmethod
                  def bar():
                  pass

                  [color=blue][color=green][color=darkred]
                  >>> foo.bar[/color][/color][/color]
                  <function bar at 0x00B445F0>[color=blue][color=green][color=darkred]
                  >>>[/color][/color][/color]

                  Comment

                  • Bengt Richter

                    #10
                    Re: Obtaining an member function by name

                    On Sat, 19 Nov 2005 14:12:25 GMT, "guy lateur" <guy.lateurNNOO SSPPAAMM@pandor a.be> wrote:
                    [color=blue]
                    >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..
                    >[/color]
                    Sorry, clean forgot about the strings.
                    [color=blue][color=green][color=darkred]
                    >>> class foo:[/color][/color][/color]
                    ... def bar(self): return self, 'bar is the name'
                    ...[color=blue][color=green][color=darkred]
                    >>> # The definition is at global scope, so 'foo' will show up[/color][/color][/color]
                    ... # in the globals() directory, which we can access with appended ['foo']
                    ...[color=blue][color=green][color=darkred]
                    >>> globals()['foo'][/color][/color][/color]
                    <class __main__.foo at 0x02EE9C2C>[color=blue][color=green][color=darkred]
                    >>> #if you want the 'bar' attribute using the string[/color][/color][/color]
                    ... getattr(globals ()['foo'], 'bar')
                    <unbound method foo.bar>[color=blue][color=green][color=darkred]
                    >>> foo.bar[/color][/color][/color]
                    <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

                    Comment

                    • Bengt Richter

                      #11
                      Re: Obtaining an member function by name

                      On Sat, 19 Nov 2005 14:12:25 GMT, "guy lateur" <guy.lateurNNOO SSPPAAMM@pandor a.be> wrote:
                      [color=blue]
                      >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..
                      >[/color]
                      Sorry, clean forgot about the strings.
                      [color=blue][color=green][color=darkred]
                      >>> class foo:[/color][/color][/color]
                      ... def bar(self): return self, 'bar is the name'
                      ...[color=blue][color=green][color=darkred]
                      >>> # The definition is at global scope, so 'foo' will show up[/color][/color][/color]
                      ... # in the globals() directory, which we can access with appended ['foo']
                      ...[color=blue][color=green][color=darkred]
                      >>> globals()['foo'][/color][/color][/color]
                      <class __main__.foo at 0x02EE9C2C>[color=blue][color=green][color=darkred]
                      >>> #if you want the 'bar' attribute using the string[/color][/color][/color]
                      ... getattr(globals ()['foo'], 'bar')
                      <unbound method foo.bar>[color=blue][color=green][color=darkred]
                      >>> foo.bar[/color][/color][/color]
                      <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

                      Comment

                      • guy lateur

                        #12
                        Re: Obtaining an member function by name

                        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


                        Comment

                        • guy lateur

                          #13
                          Re: Obtaining an member function by name

                          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


                          Comment

                          Working...