Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
python类中的输入检查函数_Python_Python 3.x_Class_Oop - Fatal编程技术网

python类中的输入检查函数

python类中的输入检查函数,python,python-3.x,class,oop,Python,Python 3.x,Class,Oop,我想对特定类的输入创建一个检查,我有以下虚构的示例: 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 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是否不同,如果是,我不希望创建NMBOOperation的实例

例如:

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'

我不太确定我做错了什么

您正在创建一个
nmbooperation
对象,
\uuuu init\uuu
方法在执行行之前立即返回该对象

self.NmbPair1 = NmbPair1
self.NmbPair2 = NmbPair2
self._add_first_nmb()
这是因为
self.check(NmbPair1,NmbPair2)
返回
None
,所以
不是self.check(NmbPair1,NmbPair2)
真的

因此,从不设置属性
sum\u a
,因为从不调用
\u add\u first\u nmb

您的
检查方法相当于:

def check(self, a, b):
    if a == b:
        return False
    else:
        return None
你可能想要

def check(self, a, b):
    return not a == b