【问题标题】:Storing and checking a boolean in a python class在 python 类中存储和检查布尔值
【发布时间】:2017-11-05 19:52:26
【问题描述】:

所以我试图创建一个对象,该对象基本上有一个构造函数,它采用两个坐标,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

【问题讨论】:

    标签: python python-3.x class boolean


    【解决方案1】:

    您的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
    

    【讨论】:

    • 有没有一种方法可以存储一个名为 isValidPt 的布尔变量?我被指示存储一个布尔变量
    • 重命名方法,在前面加上_,然后在你更改对象的任何地方(即:translateXtranslateY)做self.isValidPt = self._isValidPt
    【解决方案2】:

    构造函数主要用于初始化值。在您的情况下,构造函数检查初始值并设置验证标志。即isValidPt。 对于您创建的 p 对象的范围,它将为 True。所以你必须创建一个验证函数并在 init 和 shift 函数上调用验证函数。 检查以下内容

    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.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-09-26
      • 1970-01-01
      • 2010-10-25
      • 2012-03-10
      • 1970-01-01
      • 1970-01-01
      • 2012-02-17
      • 2012-10-15
      相关资源
      最近更新 更多