开发者

object oriented programming basics (python)

开发者 https://www.devze.com 2023-01-17 10:01 出处:网络
Level: Beginner In the following code my \'samePoint\' function returns False where i am expecting True. Any hints?

Level: Beginner

In the following code my 'samePoint' function returns False where i am expecting True. Any hints?

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

sou开发者_如何学编程rce: MIT OpenCourseWare http://ocw.mit.edu Introduction to Computer Science and Programming Fall 2008


Looking at your code

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

p.cartesian, q.cartesian are functions and you are comparing function rather than function result. Since the comparing two distinct functions, the result is False

What you should have been coding is

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


You are not calling the methods on the equal check. So you are comparing the methods to each othter.

Try:

 return (p.cartesian() == q.cartesian())


After you get the function calling thing fixed, you'll have floating point issues.

try,

def is_same_point(p1, p2, e):
    for c1, c2 in zip(c1, c2):
       if abs(c1 - c2) > e:
          return False
    return True

I'm really surprised that it's working out for you with the code sample you posted. You must have constructed it to do so. In general, you can't directly compare floating point values for equality.

A more pythonic way to write the above function is

def is_same_point(point1, point2, e):
    return not any(abs(c1 - c2) > e for c1, c2 in zip(point1, point2))

you still have to pass the e (for epsilon) around though and that's gonna get old fast.

def make_point_tester(e):
    def is_same_point(point1, point2):
        return not any(abs(c1 - c2) > e for c1, c2 in zip(point1, point2))
    return is_same_point

is_same_point = make_point_tester(.001)

You've allready run into functions being first class objects, so you shouldn't have any trouble with this code ;)

0

精彩评论

暂无评论...
验证码 换一张
取 消