[英]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: 我的电话check_angles返回以下内容而不是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. 输出正确:
my_triangle.check_angles
返回函数本身,因此您获得的文本就是该函数的描述。 To actually print the result, just do print my_triangle.check_angles()
. 要实际打印结果,只需
print my_triangle.check_angles()
。
PS. PS。 Please watch out with floating point numbers.
请当心浮点数。 As soon as you use something other than integers, the sum may not be exactly
180
. 使用整数以外的值时,总和可能不完全是
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. 如果您需要除整数以外的任何内容,那么
abs(result-180) < 1e-6
(或其他要比较的小数字)会更好。
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. 您的实现有一些小问题,因为您没有在函数中传递
self
,而没有执行self.angle1
等等。 Also, it might be useful to put the number_of_sides
into __init__
. 另外,将
number_of_sides
放入__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. 接下来,您必须将
self
作为参数提供给类中的任何方法。
def check_angles(self):
Also, you don't want to use angle1
, angle2
, or angle3
- you need to prepend those with self.
另外,您也不想使用
angle1
, angle2
或angle3
您需要在self.
添加前缀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. 最后,是一种样式:您可以返回
self.angle1 + self.angle2 + self.angle3 == 180
,因为它是布尔值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.