S
S
Sergey Ermakov2016-04-10 02:06:22
Python
Sergey Ermakov, 2016-04-10 02:06:22

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

1 answer(s)
V
Vladimir Kuts, 2016-04-10
@LOCALBEELINE

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
>>>

built-in hasattr function - you check if a class object has a property. With the built-in callable function, you can additionally make sure that this is a variable:
>>> callable(getattr(cls, 'some_var'))
False

Function execution is not interrupted.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question