如果 Python Class 中未定义变量,则引发异常

Raise an exception if a variable is not defined in Python Class

我需要制作一个 FancyTuple class 并根据需要选择性地传递五个值,FancyTuple class 在访问时应该 return 一个特定的值,例如当我传递:

然而,当访问一个未初始化的变量时,它应该抛出变量未定义的异常,例如:

我该如何实施?到目前为止我一直在尝试的是在 __ init__ 中初始化,然后在 __str __ 方法中我试图实现空值,但它无法正常工作。我也尝试了 __getattribute __ 方法但是它给出了递归代码错误?

代码如下:

class FancyTuple:
   def __init__(self, first = None, second = None, third = None, fourth = None, fifth = None):
        self.first = first
        self.second = second
        self.third = third
        self.fourth = fourth
        self.fifth = fifth


  def __str__(self, value):
      print('Value')
      if value == None:
          raise AttributeError('Accessed var is none')
    
      return f'{self.first} {self.second} {self.third} {self.fourth} {self.fifth}'

这里唯一要注意的是 __getattribute__ 将被调用用于任何属性访问,而 __getattr__ 将负责处理非法属性访问。

class FancyTuple:
    def __init__(self, first = None, second = None, third = None, fourth = None, fifth = None):
        self.first = first
        self.second = second
        self.third = third
        self.fourth = fourth
        self.fifth = fifth
    
    def __getattribute__(self, attr):
        temp = object.__getattribute__(self,attr) 
        if temp == None:
            raise Exception("Your custom exception for None attributes")
        else:
            return temp
        
    def __getattr__(self, attr):
        raise AttributeError("Your custom exception for non-existing attributes")

    def __str__(self):
        return f'{self.first} {self.second} {self.third} {self.fourth} {self.fifth}'

测试 1:

myObject = FancyTuple('dog','eagle','mouse', 'foo', 'bar')
print(myObject)
print(myObject.fifth)
print(myObject.sixth)

输出:

dog eagle mouse foo bar
bar

---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)

<ipython-input-41-b04d601ed000> in <module>()
      2 print(myObject)
      3 print(myObject.fifth)
----> 4 print(myObject.sixth)

<ipython-input-40-747793c9a3b8> in __getattr__(self, attr)
     15 
     16     def __getattr__(self, attr):
---> 17         raise AttributeError("Your custom exception for non-existing attributes")
     18 
     19     def __str__(self):

AttributeError: Your custom exception for non-existing attributes

测试 2:

myObject = FancyTuple('dog','eagle','mouse', 'foo')
print(myObject.fifth)

输出:

---------------------------------------------------------------------------

Exception                                 Traceback (most recent call last)

<ipython-input-42-2a980f7d7d01> in <module>()
      1 myObject = FancyTuple('dog','eagle','mouse', 'foo')
----> 2 print(myObject.fifth)

<ipython-input-40-747793c9a3b8> in __getattribute__(self, attr)
     10         temp = object.__getattribute__(self,attr)
     11         if temp == None:
---> 12             raise Exception("Your custom exception for None attributes")
     13         else:
     14             return temp

Exception: Your custom exception for None attributes