在python类中存储和检查布尔值

时间:2017-06-05 05:26:35

标签: python python-3.x class boolean

所以我试图创建一个基本上有一个带有两个坐标xcoordycoord的构造函数的对象。我进一步创建了移动坐标的方法,我必须检查点是否有效(有效性的标准是如果坐标超出指定范围,它应该返回False否则True)。

问题:

我的班级仅返回初始点的有效性,而不是返回的点。

我需要更正我的代码?

代码:

class Point:
    MaxScreenSize=10
    def __init__(self,x,y):
        self.xcoord=x
        self.ycoord=y
        if 0>self.xcoord or self.xcoord>Point.MaxScreenSize or 0>self.ycoord or self.ycoord>Point.MaxScreenSize:
            Point.isValidPt=False
        else:
            Point.isValidPt=True
    def translateX(self,shiftX):
        self.xcoord=self.xcoord+shiftX
    def translateY(self,shiftY):
        self.ycoord=self.ycoord+shiftY

测试代码:

我尝试了我的代码,它只为我的初始点返回isValidFunction变量(给我True而不是False以获取以下代码)

p=Point(9,2) 
p.translateX(20)
p.translateY(10)
p.isValidPt

2 个答案:

答案 0 :(得分:2)

只有在实例化类时才会计算isValidPt。而是尝试类似的事情:

代码:

class Point:
    MaxScreenSize = 10

    def __init__(self, x, y):
        self.xcoord = x
        self.ycoord = y

    def translateX(self, shiftX):
        self.xcoord = self.xcoord + shiftX

    def translateY(self, shiftY):
        self.ycoord = self.ycoord + shiftY

    @property
    def isValidPt(self):
        return (
            0 <= self.xcoord <= Point.MaxScreenSize and
            0 <= self.ycoord <= Point.MaxScreenSize
        )

测试代码:

p = Point(9, 2)
p.translateX(20)
p.translateY(10)
print(p.isValidPt)

结果:

False

答案 1 :(得分:1)

构造函数主要用于启动值。在您的情况下,构造函数检查初始值并设置validate标志。即,isValidPt。 对于您创建的p对象的范围,它将为True。因此,您必须创建验证函数并在 init 和shift函数上调用validate函数。 请检查以下

class Point:
    MaxScreenSize=10
    def __init__(self,x,y):
        self.xcoord=x
        self.ycoord=y
        self.validate()

    def validate(self):
        if 0>self.xcoord or self.xcoord>Point.MaxScreenSize or 0>self.ycoord or self.ycoord>Point.MaxScreenSize:
            Point.isValidPt=False
        else:
            Point.isValidPt=True

    def translateX(self,shiftX):
        self.xcoord=self.xcoord+shiftX
        self.validate()
    def translateY(self,shiftY):
        self.ycoord=self.ycoord+shiftY
        self.validate()
每次验证执行和更新值时,在上面的代码中

isValidPt