why does abs() function works for the position coordinate in Python?

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.

 

 

 

 

 

 

 

作者:Chuck Lu    GitHub    
posted @   ChuckLu  阅读(34)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
历史上的今天:
2021-09-17 向量内积(点乘)和外积(叉乘)概念及几何意义
2021-09-17 jQuery Migrate
2021-09-17 Best way to expose resource strings to JavaScript files in ASP.NET MVC?
2021-09-17 What's the difference between sweetalert and sweetalert2?
2021-09-17 Does javascript have an Equivalent to C#s HttpUtility.HtmlEncode? [duplicate]
2021-09-17 sweetalert2 and xss
2021-09-17 上海居住证办理条件以及流程?
点击右上角即可分享
微信分享提示