gpt4 book ai didi

python - 面向对象编程基础(python)

转载 作者:行者123 更新时间:2023-11-28 19:59:35 24 4
gpt4 key购买 nike

级别:初级

在下面的代码中,我的“samePoint”函数在我期望为 True 的地方返回 False。有什么提示吗?

import math

class cPoint:
def __init__(self,x,y):
self.x = x
self.y = y
self.radius = math.sqrt(self.x*self.x + self.y*self.y)
self.angle = math.atan2(self.y,self.x)
def cartesian(self):
return (self.x, self.y)
def polar(self):
return (self.radius, self.angle)

class pPoint:
def __init__(self,r,a):
self.radius = r
self.angle = a
self.x = r * math.cos(a)
self.y = r * math.sin(a)
def cartesian(self):
return (self.x, self.y)
def polar(self):
return (self.radius, self.angle)

def samePoint(p, q):
return (p.cartesian == q.cartesian)

>>> p = cPoint(1.0000000000000002, 2.0)
>>> q = pPoint(2.23606797749979, 1.1071487177940904)
>>> p.cartesian()
(1.0000000000000002, 2.0)
>>> q.cartesian()
(1.0000000000000002, 2.0)
>>> samePoint(p, q)
False
>>>

来源:麻省理工学院开放式课件 http://ocw.mit.edu 2008 年秋季计算机科学与编程导论

最佳答案

查看你的代码

def samePoint(p, q):
return (p.cartesian == q.cartesian)

p.cartesian、q.cartesian 是函数,您比较的是函数而不是函数结果。由于比较两个不同的函数,结果为 False

你应该编码的是

def samePoint(p, q):
return (p.cartesian() == q.cartesian())

关于python - 面向对象编程基础(python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3797219/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com