user3668129
user3668129

Reputation: 4820

How to get all class methods

I have the following classes:

class DBManagerInterface:

    @abstractmethod
    def __init__(self, table_name): raise NotImplementedError

    @abstractmethod
    def create_table(self): raise NotImplementedError

    @abstractmethod
    def drop_table(self): raise NotImplementedError



class DataBaseManager(DBManagerInterface):

    def __init__(self, table_name):
        self.table_name = table_name

    def drop_table(self):
        None

    def create_table(self):
        None


class Example:

def __init__(self, db_manager):
    self.db_manager = db_manager

def test(self):
    self.db_manager.create_table() # can't see the db_manager methods

In Example class I'm getting the DataBaseManager pointer.

I wan't to be able to see all the DataBaseManager methods (without the need to search them manually in DataBaseManager.py file)

I'm using python 3.5.2 and pycharm editor

Is it possible ?

Upvotes: 1

Views: 55

Answers (3)

Richard Nemeth
Richard Nemeth

Reputation: 1874

The reason you are not able to see the methods of the DataBaseManager class in the attribute db_manager in Example class, is because there is no reason why the variable db_manager in the __init__ method is supposed to be an instance of DataBaseManager.

You can either specify the type directly: https://docs.python.org/3/library/typing.html

Or you can check the instance type in the __init__ method:

class Example:

    def __init__(self, db_manager):
        if not isinstance(db_manager, DataBaseManager):
            raise ValueError
        self.db_manager = db_manager

Pycharm will afterwards understand the type of the attribute and show you all the possible methods for the object.

Upvotes: 1

Adam Rosenthal
Adam Rosenthal

Reputation: 488

Try
print(dir(DataBaseManager))

From the docs:

Without arguments, return the list of names in the current local scope. With an argument, attempt to return a list of valid attributes for that object.

dir([object])

Upvotes: 0

AKX
AKX

Reputation: 169398

PyCharm has no idea what db_manager could be, so it can't give you edit hints.

If your environment supports it, annotate the argument and PyCharm can do type inference from there:

    def __init__(self, db_manager: DBManagerInterface):
        self.db_manager = db_manager

or if that's not supported, you can add an annotation in a docstring:

    def __init__(self, db_manager):
        """
        :type db_manager: DBManagerInterface
        """
        self.db_manager = db_manager

Upvotes: 2

Related Questions