0

So I have this thing I don’t know if I can do on python. I want to handle access to undefined variables. Example:

class example():
     def __init__():
          self.variableA = 'jaa'
     def set_b(self):
          self.variableB = 'nope'

Here if I instantiate a object X of example and try to access variableB without calling x.set_b() I will get an Class has no attribute error. Is there any way to dig into this exception? I would like to return and error with a custom message.

eljiwo
  • 687
  • 1
  • 8
  • 29
  • 1
    you probably should read about [`property` decorator](https://docs.python.org/3/library/functions.html#property) – Azat Ibrakov Sep 24 '19 at 13:22
  • also [this thread](https://stackoverflow.com/questions/2627002/whats-the-pythonic-way-to-use-getters-and-setters) may help – Azat Ibrakov Sep 24 '19 at 13:22
  • You could implement [`__getattr__`](https://docs.python.org/3/reference/datamodel.html#object.__getattr__) in you class (or handle `AttributeError` exception). – Winand Sep 24 '19 at 13:25

1 Answers1

1

May I suggest to do the following:

class Example():
    def __init__(self):
        self.variableA = 'jaa'
        self._variableB = None

    @property
    def variableB(self):
        if self._variableB is None:            
            return 'Sorry, you need to set this using `Set_b` first'
            # better would probably be
            # raise AttributeError("'Sorry, you need to set this using `Set_b`")

        return self._variableB

    @variableB.setter
    def variableB(self, value):
        raise AttributeError("'Sorry, you need to set this using `Set_b`")

    def set_b(self):
        self._variableB = 'nope'

example = Example()
print(example.variableB)  # Sorry, you need to set this using `Set_b` first
try:
    example.variableB = 'mymy'
except Exception as error:
    print(repr(error))  # AttributeError('Sorry, you need to set this using `Set_b`)

example.set_b()
print(example.variableB)  # 'nope
Sebastian Loehner
  • 1,302
  • 7
  • 5