By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
448,678 Members | 1,129 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 448,678 IT Pros & Developers. It's quick & easy.

Using getattr to access inherited methods

P: 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: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

Jul 18 '05 #1
Share this question for a faster answer!
Share on Google+

This discussion thread is closed

Replies have been disabled for this discussion.