Should I write
class MyClass:
def __init__(self):
self.field = 0
or
class MyClass:
def __init__(self):
field = 0
Is there any difference between these statements?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Yes, you must use the
selfvariable to set the properties of Python objects/instances.In the second case, you’re just creating a local variable in
__init__, not defining a property.You may be misled by the way that you can just use raw assignments in
classblocks to set class properties:The behaviour in
classblocks is unusual, and you don’t get similar behaviour inside methods.