8

I am a Python beginner and my main language is C++. You know in C++, it is very common to separate the definition and implementation of a class. (How) Does Python do that? If not, how to I get a clean profile of the interfaces of a class?

updogliu
  • 6,066
  • 7
  • 37
  • 50

4 Answers4

5

There is no such concept in Python. If I'm understanding your needs correctly, "a clean profile" should be generated by proper class documentation.

You can also use Python's introspection capabilities to programatically access all the methods of a class.

Community
  • 1
  • 1
Yuval Adam
  • 161,610
  • 92
  • 305
  • 395
2

You may want to implement a sort of "interface" which can be imported separately from your implementation. In python, this is called an Abstract Base Class and is provided via the builtin abc module

# mymodule/types.py
# --------------------------------------------

import abc

class AbstractSomeClass(abc.ABC):
  some_property: str

  @abc.abstractmethod
  def somemethod(self, some_param: str) -> int:
    raise NotImplementedError


# mymodule/someclass.py
# --------------------------------------------

from mymodule.types import AbstractSomeClass

class SomeClass(AbstractSomeClass):
  def __init__(self):
    self.some_property = "some val"

  def somemethod(self, some_param: str) -> int:
    return 5


# mymodule/file_causing_circular_import.py
# --------------------------------------------
# Refactored to use the ABC instead of the implementation

from mymodule.types import AbstractSomeClass

def mymethod(instance: AbstractSomeClass):
  instance.somemethod("some param")
`
seveibar
  • 4,403
  • 4
  • 30
  • 31
1

Python programming is different in many aspects from c++. If what you want to know is how to write quality, professional level code in python then this is a good article to start with. Good luck.

Emil
  • 370
  • 1
  • 5
1

    For some reason, many Python programmers combine the class and its implementation in the same file; I like to separate them, unless it is absolutely necessary to do so.
    That's easy. Just create the implementation file, import the module in which the class is defined, and you can call it directly.
    So, if the class - ShowMeTheMoney - is defined inside class1_file.py, and the file structure is:

  
/project
    /classes
           /__init__.py
           /class1_file.py
           /class2_file.py
    /class1_imp_.py   
  

(BTW, the file and class names must be different; the program will fail if the class and the file names are the same.)
    You can implement it in the class1_imp_.py using:

 
   # class1_imp_.py
   import classes.class1_file as any_name

   class1_obj = any_name.ShowMeTheMoney()
   #continue the remaining processes


 

Hope this helps.

Kneel-Before-ZOD
  • 4,141
  • 1
  • 24
  • 26