FazBrowse GitHub Viewer
|
Trending
|
URL:
|
Home
Tools:
[Download Repo ZIP]
[View Raw Code]
[Original HTTPS Page]
example-code/09-pythonic-obj/vector2d_v1.py at master · TheWaveLab/example-code · GitHub
TheWaveLab
/
example-code
Public
forked from
fluentpython/example-code
Notifications
You must be signed in to change notification settings
Fork
0
Star
0
Code
Pull requests
0
Actions
Projects
Security and quality
0
Insights
Additional navigation options
Code
Pull requests
Actions
Projects
Security and quality
Insights
Expand file tree
Breadcrumbs
example-code
/
09-pythonic-obj
/
vector2d_v1.py
Copy path
More file actions
More file actions
Latest commit
History
History
History
76 lines (59 loc) · 1.57 KB
Breadcrumbs
example-code
/
09-pythonic-obj
/
vector2d_v1.py
Copy path
File metadata and controls
76 lines (59 loc) · 1.57 KB
Raw
Copy raw file
Download raw file
Open symbols panel
Edit and raw actions
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
"""
A 2-dimensional vector class
>>> v1 = Vector2d(3, 4)
>>> print(v1.x, v1.y)
3.0 4.0
>>> x, y = v1
>>> x, y
(3.0, 4.0)
>>> v1
Vector2d(3.0, 4.0)
>>> v1_clone = eval(repr(v1))
>>> v1 == v1_clone
True
>>> print(v1)
(3.0, 4.0)
>>> octets = bytes(v1)
>>> octets
b'd
\\
x00
\\
x00
\\
x00
\\
x00
\\
x00
\\
x00
\\
x08@
\\
x00
\\
x00
\\
x00
\\
x00
\\
x00
\\
x00
\\
x10@'
>>> abs(v1)
5.0
>>> bool(v1), bool(Vector2d(0, 0))
(True, False)
Test of ``.frombytes()`` class method:
>>> v1_clone = Vector2d.frombytes(bytes(v1))
>>> v1_clone
Vector2d(3.0, 4.0)
>>> v1 == v1_clone
True
"""
from
array
import
array
import
math
class
Vector2d
:
typecode
=
'd'
def
__init__
(
self
,
x
,
y
):
self
.
x
=
float
(
x
)
self
.
y
=
float
(
y
)
def
__iter__
(
self
):
return
(
i
for
i
in
(
self
.
x
,
self
.
y
))
def
__repr__
(
self
):
class_name
=
type
(
self
).
__name__
return
'{}({!r}, {!r})'
.
format
(
class_name
,
*
self
)
def
__str__
(
self
):
return
str
(
tuple
(
self
))
def
__bytes__
(
self
):
return
(
bytes
([
ord
(
self
.
typecode
)])
+
bytes
(
array
(
self
.
typecode
,
self
)))
def
__eq__
(
self
,
other
):
return
tuple
(
self
)
==
tuple
(
other
)
def
__abs__
(
self
):
return
math
.
hypot
(
self
.
x
,
self
.
y
)
def
__bool__
(
self
):
return
bool
(
abs
(
self
))
# BEGIN VECTOR2D_V1
@
classmethod
# <1>
def
frombytes
(
cls
,
octets
):
# <2>
typecode
=
chr
(
octets
[
0
])
# <3>
memv
=
memoryview
(
octets
[
1
:]).
cast
(
typecode
)
# <4>
return
cls
(
*
memv
)
# <5>
# END VECTOR2D_V1
Back
|
FazBrowse Home
|
New Git URL