MathiasDesch MathiasDesch - 1 month ago 13
Python Question

Python constructors convention

I wonder if there is any convention regarding constructor in Python. If I have a constructor doing nothing, I can basically not writing it and everything will work just fine.
However when I'm using Pycharm, it is recommending me (warning) to write an empty constructor:

__init__:
pass


I have not find anything regarding this problem in the PEP8. I am wondering if Pycharm just come out with a new convention or if there is a reason behind that ?

Thanks.

Vor Vor
Answer

I think it's opinion based, but I will share rules that I try to follow: 1. Declare all instance variables in constructor, even if they are not set yet

def __init__(self, name):
    self.name = name
    self.lname = None
  1. Do not do any logic in the constructor. You will benefit from this when will try to write unittests.

  2. And of course if it's not necessary dont' add it.