Consider the following class:
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
My coworkers tend to define it like this:
class Person:
name = None
age = None
def __init__(self, name, age):
self.name = name
self.age = age
The main reason for this is that their IDE of choice shows the properties for autocompletion.
Personally, I dislike the latter one, because it makes no sense that a class has those properties set to None
.
Which one would be better practice and for what reasons?
__init__
already provides autocompletion etc. Also, usingNone
prevents the IDE to infer a better type for the attribute, so it's better to use a sensible default instead (when possible).typing
module, which allow you to provide hints to the IDE and linter, if that sort of thing tickles your fancy...self
. Even ifself.name
orself.age
were not assigned in__init__
they would not show up in the instanceself
, they only show up in the classPerson
.