Consider the following Python code:
class a_class:
defined_var = 1
def a_function(self):
self.defined_var = 2
self.undefined_var = 3
The possibility to assign a value to a variable (and then implicitly declare it) that I did not declared at the beginning of the class (like I do for
undefined_var
in the previous example) is creating me several problems, since for huge classes I forget what I define and I what I don't.
I know that this question may sound silly. I've used to develop using C/C++/Java for a long time where the definition of variables in a class is mandatory...
Is there a way to avoid this? I mean, I would like a behavior like in C/C++/Java where I get an error if I use an undefined variable.
By default, python instances have a __dict__
- a dictionary that stores all of the object's attributes. This is what allows them to store arbitrary attributes. You can suppress the creation of the __dict__
by defining __slots__
. This is a class-level variable listing the names of all attributes instances of the class can have. If a class has __slots__
, trying to assign to an undefined attribute will throw an exception.
Example:
class MyClass:
__slots__ = ['defined_var']
def a_function(self):
self.defined_var = 2
obj = MyClass()
obj.a_function()
obj.undefined_var = 3 # throws AttributeError