Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python: print non inherited methods

I am trying to print a list of the methods that have not been inherited from other classes (e.g.., not inheritted from object or another base class). As an example say I have the following class:

class Point:
    def __init__(self, x, y):
        self.__x=x
        self.__y=y

calling this method should print: [__init__] without __str__ (inheritted from object).

I've tried:

dir(Point) 

but the problem is that it includes already inheritted methods.

like image 287
Teererai Marange Avatar asked Oct 27 '25 08:10

Teererai Marange


2 Answers

To print the non-inherited attributes of an object, such as a class object, use vars which checks the __dict__ of that object:

In [1]: class Point:
   ...:     def __init__(self, x, y):
   ...:         self.__x=x
   ...:         self.__y=y
   ...:

In [2]: vars(Point)
Out[2]:
mappingproxy({'__dict__': <attribute '__dict__' of 'Point' objects>,
              '__doc__': None,
              '__init__': <function __main__.Point.__init__>,
              '__module__': '__main__',
              '__weakref__': <attribute '__weakref__' of 'Point' objects>})

Since a method is merely a callable object in the class, you can check for it using something to the effect of:

In [3]: for k, v in vars(Point).items():
   ...:     if callable(v):
   ...:         print(k)
   ...:
__init__
like image 138
juanpa.arrivillaga Avatar answered Oct 28 '25 22:10

juanpa.arrivillaga


You can look into the __dict__ of the class itself:

import types

def list_methods(t):
    for name, item in t.__dict__.items():
        if isinstance(item, types.FunctionType):
            print(name)

t is a class object here, not an instance of a class. If you want to operate on instances, replace t.__dict__.items() with type(t).__dict__.items() in the loop.

like image 38
Mad Physicist Avatar answered Oct 28 '25 20:10

Mad Physicist