selective (inheriting?) dir()?
Skip Montanaro
skip at pobox.com
Mon Apr 21 10:06:14 EDT 2014
Before I get up to my neck in gators over this, I was hoping perhaps
someone already had a solution. Suppose I have two classes, A and B,
the latter inheriting from the former:
class A:
def __init__(self):
self.x = 0
class B(A):
def __init__(self):
A.__init__(self)
self.y = 1
inst_b = B()
Now, dir(inst_b) will list both 'x' and 'y' as attributes (along with
the various under under attributes). Without examining the source, is
it possible to define some kind of "selective" dir, with a API like
def selective_dir(inst, class_): pass
which will list only those attributes of inst which were first defined
in (some method defined by) class_? The output of calls with different
class_ args would yield different lists:
selective_dir(inst_b, B) -> ['y']
selective_dir(inst_b, A) -> ['x']
I'm thinking some sort of gymnastics with inspect might do the trick,
but after a quick skim of that module's functions nothing leapt out at
me. OTOH, working through the code objects for the methods looks
potentially promising:
>>> B.__init__.im_func.func_code.co_names
('A', '__init__', 'y')
>>> A.__init__.im_func.func_code.co_names
('x',)
Thx,
Skip
More information about the Python-list
mailing list