不支持的操作数类型: '+':'int' 和 'classobj

0 投票
2 回答
1825 浏览
提问于 2025-04-18 02:30

我正在尝试找出两条直线交点的坐标,但在交点的计算过程中遇到了这个错误:

unsupported operand type(s) for +: 'int' and 'classobj' 

我该怎么做才能解决这个问题呢?

class Point:
    def __init__(self,x,y):
        self.x=x
        self.y=y

class Line1:
    def __init__(self,a1,b1,c1):
        self.a1=a1
        self.b1=b1
        self.c1=c1
    def slope(self):
        try:
            return -self.a1/self.b1
        except ZeroDivisionError:
            return None
    def isonline(self,Point):
        if (self.a1*Point.x+self.b1*Point.y+self.c1)==0:
            return True
        else:
            return False

class IntersectionPoint:
    def __init__(self,a2,b2,c2):
        self.a2=a2
        self.b2=b2
        self.c2=c2            
    def intersect(self,Line1): 
        xcord=(-Line1.a1/Line1.b1)+(self.a2/self.b2)-Line1.c1+self.c2
        ycord=(-Line1.a1/Line1.b1)*xcord-self.c2
        return 'True. The intersection point is: I' (xcord,ycord) 


coordinatesPoint=Point(1,1)
abcfromLine=Line1(2,-1 ,-3)
Line2=IntersectionPoint(3,-1 -1, Line1)
print abcfromLine.slope()
print abcfromLine.isonline(coordinatesPoint)
print Line2.intersect(abcfromLine)

2 个回答

0

Line2=IntersectionPoint(3,-1 -1, Line1)

改成

Line2=IntersectionPoint(3,-1, -1)

你传入了4个参数,但少了一个逗号

1

你传入了一个 类对象IntersectionPoint() 这个函数里:

Line2=IntersectionPoint(3,-1 -1, Line1)

Line1 是一个类。它是这个函数的第三个参数,因为在两个 -1 参数之间没有逗号。所以,你把 3 赋值给了 a2,把 -2 赋值给了 b2,把 Line1 赋值给了 c2

intersect 方法中,你又把这个类对象和一个整数相加:

Line1.c1+self.c2

这里的 self.c2 就是你的 Line1 类。

你想要的是:

Line2 = IntersectionPoint(3, -1, -1)

而不是这样。

接下来,你会在这一行遇到错误:

return 'True. The intersection point is: I' (xcord,ycord) 

因为这就像是试图把字符串当作函数来用。你可能在这里缺少了字符串格式化的操作,或者缺少了一个逗号:

return 'True. The intersection point is: (%d, %d)' % (xcord,ycord) 

或者

return 'True. The intersection point is: I', (xcord,ycord) 

撰写回答