我想创建一个特定类的输入检查,我有以下组成的例子:
class NmbPair:
def __init__(self, a = None, b = None):
self.a = a
self.b = b
def __eq__(self, other):
if self.a == other.a and self.b == other.b:
return True
return False
class NmbOperation:
def __init__(self, *, NmbPair1, NmbPair2):
if not self.check(NmbPair1, NmbPair2): ## this is the check
return
self.NmbPair1 = NmbPair1
self.NmbPair2 = NmbPair2
self._add_first_nmb()
def check(self, a, b):
if a == b:
return False
def _add_first_nmb(self):
self.sum_a = self.NmbPair1.a + self.NmbPair2.a
所以我想检查输入NmbPairs是不一样的,如果是,我不想创建NmbOperation的实例。
例如:
t1 = NmbPair(2, 3)
t2 = NmbPair(2, 2)
Op1 = NmbOperation(NmbPair1 = t1, NmbPair2 = t2)
print(Op1.sum_a)
但这引发了错误:
AttributeError: 'NmbOperation' object has no attribute 'sum_a'
我不太确定我做错了什么
答案 0 :(得分:1)
您正在创建一个NmbOperation
对象,__init__
方法在执行行之前会立即返回
self.NmbPair1 = NmbPair1
self.NmbPair2 = NmbPair2
self._add_first_nmb()
这是因为self.check(NmbPair1, NmbPair2)
返回None
,因此not self.check(NmbPair1, NmbPair2)
为True
。
因此,永远不会设置属性sum_a
,因为永远不会调用_add_first_nmb
。
您的check
方法相当于:
def check(self, a, b):
if a == b:
return False
else:
return None
你可能想要
def check(self, a, b):
return not a == b