Answer the question
In order to leave comments, you need to log in
How to catch an error when working in a class?
Hello.
The question is, how, when working in a class, to catch with the help of magic methods (def __method__ ), an error that the variable is not defined?
I need that when I access a variable (defined in the self-class) in any function in my class, it will be automatically created if it does not exist and after its creation the function will continue to be executed or will it stop?
Answer the question
In order to leave comments, you need to log in
Well, you can, for example:
>>> class SomeClass:
... pass
...
>>> cls = SomeClass()
>>> print cls.some_var
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: SomeClass instance has no attribute 'some_var'
>>> print hasattr(cls, 'some_var')
False
>>> if not hasattr(cls, 'some_var'):
... cls.some_var = 1
...
>>> print cls.some_var
1
>>> print hasattr(cls, 'some_var')
True
>>>
>>> callable(getattr(cls, 'some_var'))
False
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question