Using getattr to access inherited methods

Discussion in 'Python' started by daishi, Jul 25, 2003.

  1. daishi

    daishi Guest

    Hi,

    The following code appears to be doing what I'd expect, but
    I'm wondering if someone could confirm that there aren't any
    "gotchas" hidden in using methods accessed in this way. In
    particular, should I be concerned that in the example below,
    f is different from g and h when applying f to instances of
    test.Sub? For my simple example things appear reasonable, but ...

    Thanks,
    Daishi

    ---test.py
    class Super:
    def __init__(self):
    self.fn = None
    def applyFn(self, arg):
    if self.fn:
    return self.fn(arg)
    else:
    return "No function defined"

    class Sub(Super):
    def __init__(self):
    self.fn = self.aFn
    def aFn(self, x):
    return x+2

    ---Python shell
    % python
    Python 2.2.3+ (#1, Jul 5 2003, 11:04:18)
    [GCC 3.3.1 20030626 (Debian prerelease)] on linux2
    Type "help", "copyright", "credits" or "license" for more information.
    >>> import test
    >>> test.Super

    <class test.Super at 0x816a2bc>
    >>> test.Sub

    <class test.Sub at 0x8170bd4>
    >>> s = test.Sub()
    >>> s.__class__

    <class test.Sub at 0x8170bd4>
    >>> f = getattr(test.Super, 'applyFn')
    >>> g = getattr(test.Sub, 'applyFn')
    >>> h = getattr(s.__class__, 'applyFn')
    >>> f

    <unbound method Super.applyFn>
    >>> g

    <unbound method Sub.applyFn>
    >>> h

    <unbound method Sub.applyFn>
    >>> f(s, 3)

    5
    >>> g(s, 3)

    5
    >>> h(s, 3)

    5
    >>>
     
    daishi, Jul 25, 2003
    #1
    1. Advertisements

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Jim Schueler
    Replies:
    2
    Views:
    533
  2. Tron Thomas
    Replies:
    10
    Views:
    1,329
    Tom Widmer
    Nov 10, 2004
  3. Replies:
    4
    Views:
    488
  4. Nathan Harmston

    recursion error using setattr and getattr

    Nathan Harmston, Jun 7, 2007, in forum: Python
    Replies:
    0
    Views:
    376
    Nathan Harmston
    Jun 7, 2007
  5. 7stud --
    Replies:
    11
    Views:
    772
    7stud --
    Nov 9, 2007
  6. Kenneth McDonald
    Replies:
    5
    Views:
    645
    Kenneth McDonald
    Sep 26, 2008
  7. Replies:
    2
    Views:
    266
    -berlin.de
    Aug 22, 2006
  8. Catherine M Moroney
    Replies:
    5
    Views:
    214
    Gregory Ewing
    Nov 22, 2013
Loading...