如何修复“'NoneType'对象没有属性'格式'”错误?

时间:2019-07-14 21:47:15

标签: python-3.x

我的硬件问题之一是要求“设计一个名为Point的类,以x和y坐标表示一个点:

  • 两个专用数据字段xy,它们分别使用getter方法表示坐标。
  • 构造器,该构造器使用默认坐标(0,0)构造具有指定坐标的点。
  • 名为distance的方法,该方法返回从该点到Point类型的另一点的距离。
  • 名为isNearBy(p1)的方法,如果点True接近该点,则返回p1。如果两个点的距离小于5,则它们是接近的。
  • 实施__str__方法以返回(x,y)形式的字符串。

为该类绘制UML图,然后实现该类。编写一个测试程序,提示用户输入两个点,显示它们之间的距离,并指示它们是否彼此靠近。

样本运行1:

Enter the x-coordinate of point1: 2.1
Enter the y-coordinate of point1: 2.3
Enter the x-coordinate of point2: 19.1
Enter the y-coordinate of point2: 19.2
The distance between the two points is 23.97
The two points are not near to other

示例2:

Enter the x-coordinate of point1: 2.1
Enter the y-coordinate of point1: 2.3
Enter the x-coordinate of point2: 2.3
Enter the y-coordinate of point2: 4.2
The distance between the two points is 1.91
The two points are near to other

我的代码:

import math
class Point:
    def __init__(self, x, y):
        self.__x = x
        self.__y = y
    def distance(self, p):
        return math.sqrt(math.pow(self.__x - p.__x, 2) + math.pow(self.__y - p.__y, 2))  
    def isNearBy(self, p):
        if self.distance(p) < 5:
            return True
        else:
            return False
    def __str(self):
        return '(' + str(self.__x) + ', ' + str(self.__y) + ')'

def main():
    x1, y1, x2, y2 = input('Enter two points x1, y1, x2, y2: ')
    print (x1+str(1), x2+str(2), y1+str(3), y2+str(4))
    p1 = Point(x1, y1)
    p2 = Point(x2, y2)
    print ('The distance between the two points is {:.2f}').format(p1.distance(p2))
    if(p1.isNearBy(p2)):
        print ('The two points are near each other.')
    else:
        print ('The two points are not near other.') 
main()

我想修复此错误:

Traceback (most recent call last): 
  File "main.py", line 30, in  
    main() 
  File "main.py", line 25, in main 
    print ('The distance between the two points is {:.2f}').format(p1.distance(p2)) 
AttributeError: 'NoneType' object has no attribute 'format'

谢谢!

0 个答案:

没有答案