Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 474
MathiasDesch Avatar asked Jul 30 '26 21:07

MathiasDesch


1 Answers

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.

like image 137
Vor Avatar answered Aug 01 '26 09:08

Vor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!