updogliu
updogliu

Reputation: 6255

Separating class definition and implementation in python

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?

Upvotes: 10

Views: 4278

Answers (4)

seveibar
seveibar

Reputation: 4943

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")
`

Upvotes: 3

Kneel-Before-ZOD
Kneel-Before-ZOD

Reputation: 4221

    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.

Upvotes: 1

Emil
Emil

Reputation: 380

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.

Upvotes: 1

Yuval Adam
Yuval Adam

Reputation: 165242

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.

Upvotes: 5

Related Questions