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). – Bakuriu Aug 27 '14 at 17:39__slots__
to your class. – Bachsau Apr 16 '18 at 16:06typing
module, which allow you to provide hints to the IDE and linter, if that sort of thing tickles your fancy... – c z Apr 30 '18 at 13:57self
. 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
. – jolvi May 27 '18 at 09:15def instx(self): return self.x
@classmethod def classx(cls): return test.x
def gety(self): print (self.y) print (test.y) return self.y a=test(2) print(a.instx()) print(a.classx()) a.gety()
– MattW Apr 10 '19 at 22:04Output:
2 1 4 7 `