On 4/21/2014 10:06 AM, Skip Montanaro wrote:
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',)

You can permanently affect dir(ob) with a special method.

object.__dir__(self)

Called when dir() is called on the object. A sequence must be returned. dir() converts the returned sequence to a list and sorts it.

From outside the class, you get the attributes defined directly in a class klass as the difference of set(dir(klass) and the union of set(dir(base)) for base in klass.__bases__. To include attributes set in __new__ and __init__, replace klass with klass().

--
Terry Jan Reedy

--
https://mail.python.org/mailman/listinfo/python-list

Reply via email to