Velocity Reviews - Computer Hardware Reviews

Velocity Reviews > Newsgroups > Programming > Python > Using getattr to access inherited methods

Thread Tools

Using getattr to access inherited methods

Posts: n/a

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 ...

class Super:
def __init__(self):
self.fn = None
def applyFn(self, arg):
if self.fn:
return self.fn(arg)
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:1
[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)

>>> g(s, 3)

>>> h(s, 3)


Reply With Quote

Thread Tools

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are On
Pingbacks are On
Refbacks are Off

Similar Threads
Thread Thread Starter Forum Replies Last Post
'Class.inherited' v. 'inherited' syntax inside Class 7stud -- Ruby 11 11-09-2007 06:45 PM
recursion error using setattr and getattr Nathan Harmston Python 0 06-07-2007 11:23 AM
Using set and get methods in an inherited class Java 4 02-01-2007 01:41 AM
OO Perl - How to maintain class state when using inherited methods? Perl Misc 2 08-22-2006 10:11 AM
Derived methods hiding inherited methods Tron Thomas C++ 10 11-10-2004 09:32 AM