When a function of a class is written as a property in Python, is it possible to throw an error when calling a function (setter) that does not exist?

Asked 2 years ago, Updated 2 years ago, 18 views

Python has written the following code:

 class Test:
    def __init__(self):
        self.hello = 0

    @property
    def test(self):
        return self.hello

    @test.setter
    det test(self, hello):
        self.hello = hello

if __name__ == '__main__':
    t = Test()
    t.test = 1
    t.test2 = 2 # I want to make an error here.

I keep making typos in the method name, but I keep making mistakes because there is no error in test2. I want to make an error when I count a function that doesn't exist in the first place. Is there any way to make me throw an error?

(We have confirmed that an AttributeError occurs if you call a getter immediately without substituting the value. I wonder if I should check this first and then proceed with the setter.)

python

2022-09-22 21:33

1 Answers

Hello.

It's best not to make a typo, but you can use __slots__ to declare the properties you want to use in advance.

class Test(object):

  __slots__ = ['hello']

  def __init__(self):
    self.hello = 0

  @property
  def test(self):
    return self.hello

  @test.setter
  def test(self, hello):
    self.hello = hello

if __name__ == '__main__':
    t = Test()
    t.test = 1
    t.test2 = 2

However, as you can see above, __slot__ requires a 'new style' class, such as class A(object), which is available from Python 2.2.

If you need to use the 'old style' class, you can override __setattr__ as follows.

class Test:

  def __setattr__(self, name, value):
    allowed = ('hello', 'test')
    if name in allowed:
      self.__dict__[name]  = value
    else:
      raise AttributeError('No attribute: %s' % name)

  def __init__(self):
    self.hello = 0

  @property
  def test(self):
    return self.hello

  @test.setter
  def test(self, hello):
    self.hello = hello

if __name__ == '__main__':
    t = Test()
    t.test = 1
    t.test2 = 2


2022-09-22 21:33

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.