简体   繁体   中英

Beginner python: what's wrong with my call to check_angles? (or the method itself, if it's that)

My call check_angles returns the following instead of True:

<bound method Triangle.check_angles of <Triangle object at 0x7fb209a66b50>>

Here's the code:

class Triangle(object):
    number_of_sides = 3
    def __init__(self, angle1, angle2, angle3):
        self.angle1 = angle1
        self.angle2 = angle2
        self.angle3 = angle3
    def check_angles():
        if angle1 + angle2 + angle3 == 180:
            return True
        else:
            return False

my_triangle = Triangle(60, 60, 60)

(print my_triangle.number_of_sides)
(print my_triangle.check_angles)

You're missing () at the end of the method.

The output is correct: my_triangle.check_angles returns the function itself, so the text you get is the description of that function. To actually print the result, just do print my_triangle.check_angles() .

PS. Please watch out with floating point numbers. As soon as you use something other than integers, the sum may not be exactly 180 . It will be a number very close to it. If you need anything other than integers, then abs(result-180) < 1e-6 (or some other small number to compare to) will be better.

You have to add the parantheses to call the function. Do.

class Triangle(object):
    number_of_sides = 3
    def __init__(self, angle1, angle2, angle3):
        self.angle1 = angle1
        self.angle2 = angle2
        self.angle3 = angle3
    def check_angles(self):
        if self.angle1 + self.angle2 + self.angle3 == 180:
            return True
        else:
            return False

my_triangle = Triangle(60, 60, 60)

print my_triangle.number_of_sides
print my_triangle.check_angles()

Your implementation had slight problems, since you don't pass self in the function and do self.angle1 and so on. Also, it might be useful to put the number_of_sides into __init__ .

You're missing the parentheses to the method call, first.

Next, you have to provide self as a parameter to any method in a class.

def check_angles(self):

Also, you don't want to use angle1 , angle2 , or angle3 - you need to prepend those with self. before you can use them in the proper scope.

Finally, a style thing: You could just return self.angle1 + self.angle2 + self.angle3 == 180 , since it's boolean.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM