面向对象编程基础知识(python)

2 python oop

级别:初学者

在下面的代码中,我的'samePoint'函数返回False,我期待True.任何提示?

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
>>> 
Run Code Online (Sandbox Code Playgroud)

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

pyf*_*unc 6

看着你的代码

def samePoint(p, q):
    return (p.cartesian == q.cartesian)
Run Code Online (Sandbox Code Playgroud)

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

你应该编码的是

def samePoint(p, q):
    return (p.cartesian() == q.cartesian())
Run Code Online (Sandbox Code Playgroud)