Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #70463
| Date | 2014-04-21 09:06 -0500 |
|---|---|
| Subject | selective (inheriting?) dir()? |
| From | Skip Montanaro <skip@pobox.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.9408.1398089649.18130.python-list@python.org> (permalink) |
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
Back to comp.lang.python | Previous | Next — Next in thread | Find similar | Unroll thread
selective (inheriting?) dir()? Skip Montanaro <skip@pobox.com> - 2014-04-21 09:06 -0500
Re: selective (inheriting?) dir()? Steven D'Aprano <steve+comp.lang.python@pearwood.info> - 2014-04-21 15:28 +0000
Re: selective (inheriting?) dir()? Skip Montanaro <skip@pobox.com> - 2014-04-21 10:52 -0500
csiph-web