Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why is defining an object variable outside of __init__ frowned upon? [duplicate]

Tags:

python

I sometimes define an object variable outside of __init__. plint and my IDE (PyCharm) complain.

class MyClass():
    def __init__(self):
        self.nicevariable = 1   # everyone is happy

    def amethod(self):
        self.uglyvariable = 2   # everyone complains

plint output:

W:  6, 8: Attribute 'uglyvariable' defined outside __init__ (attribute-defined-outside-init)

Why is this a incorrect practice?

like image 982
WoJ Avatar asked Aug 06 '14 11:08

WoJ


People also ask

Is it OK to define instance attribute outside init?

It is perfectly possible for instance attributes to be defined outside of your __init__ , you need to be careful about how your class is used.

What would you call a variable defined outside a constructor?

Instance variables are generally defined/initialized within the constructor. But instance variables can also be defined/initialized outside the constructor, e.g. in the other methods of the same class.

How instance variables are different from class variables in Python?

Python instance variables can have different values across multiple instances of a class. Class variables share the same value among all instances of the class. The value of instance variables can differ across each instance of a class. Class variables can only be assigned when a class has been defined.

What is the use of instance variable in Python?

What is an Instance Variable in Python? If the value of a variable varies from object to object, then such variables are called instance variables. For every object, a separate copy of the instance variable will be created. Instance variables are not shared by objects.


1 Answers

Python allows you to add and delete attributes at any time. There are two problems with not doing it at __init__

  1. Your definitions aren't all in one place
  2. If you use it in a function, you may not have defined it yet

Note that you can fix the above problem of setting an attribute later by definin it in __init__ as:

self.dontknowyet = None      # Everyone is happy
like image 89
stark Avatar answered Sep 22 '22 14:09

stark