why does abs() function works for the position coordinate in Python?
I am looking at the Python document for turtle graphics, it has an example on drawing the turtle star. the program is as follow:
from turtle import *
color('red', 'yellow')
begin_fill()
while True:
forward(200)
left(170)
if abs(pos()) < 1:
break
end_fill()
done()
I don't understand why the abs(pos())
works? The abs()
function takes a single argument, but the pos()
function returns a position (x,y) coordinate. I know the program works, just don't understand why. I tried it on the Python interpreter with abs((-0.00,0.00))
, it returns error. Please help!
回答1
pos()
returns a turtle.Vec2D, not a tuple. You can make abs()
work for any type by implementing __abs__()
. In the case of turtle, __abs__()
returns (self[0]**2 + self[1]**2)**0.5
as per the turtle source code here.
回答2
The pos()
is not returning a tuple with x and y coordinate, instead it is returning an object of type turtle.Vec2D
, this can be verified using:
>>> type(pos())
>>> turtle.Vec2D
Further if you run dir(pos())
you may get:
['__abs__', '__add__', ... '__class__','count', 'index', 'rotate']
So the turtle.Vec2D
object has its own __abs__
implementation, but a generic tuple
has no such implementation.
How abs() works for 2D vector
I can't understand how abs() function works with pos() method from Turle graphics:
from turtle import *
while True:
forward(200)
left(170)
print(str(abs(pos()))+"\t\t"+str(pos()))
if abs(pos()) < 1:
break
The abs() function change vector like this:
(3.04,34.73) >> 34.862297099063255
Is there any mathematical explanation of this?
回答1
abs(x)
returns either the absolute value for x
if x
is an integer or a custom value for x
if x
implements an __abs__()
method. In your case, pos()
is returning an object of type Vec2D
, which implements the __abs__()
method like the following:
def __abs__(self):
return (self[0]**2 + self[1]**2)**0.5
So the value returned by abs(x)
is here the length of this vector. In this case, this makes sense also because that way you get a one-dimensional representation of this vector.