-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnumerictypes.py
More file actions
72 lines (48 loc) · 1.56 KB
/
Copy pathnumerictypes.py
File metadata and controls
72 lines (48 loc) · 1.56 KB
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
from array import array
import math
class Vector:
def __init__(self, x=0, y=0, z=0):
self.x = x
self.y = y
self.z = z
def __repr__(self):
return 'Vector(%r, %r, %r)' % (self.x, self.y, self.z)
def __abs__(self):
return math.hypot(self.x, self.y, self.z)
# By default User defined instances considered true, unless either __boo__ or __len__ is implemented
def __bool__(self):
return bool(abs(self))
# Return result without changing operands
def __add__(self, other):
x = self.x + other.x
y = self.y + other.y
z = self.z + other.z
return Vector(x, y, z)
def __mul__(self, scalar):
return Vector(self.x * scalar, self.y * scalar, self.z * scalar)
class Vector3d:
typecode = 'd'
def __init__(self, x, y, z):
self.x = float(x)
self.y = float(y)
self.z = float(z)
def __iter__(self):
return (i for i in (self.x, self.y, self.z))
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, self.z)
def __bool__(self):
return bool(abs(self.x, self.y, self.z))
v1 = Vector(3, 4, 8)
v2 = Vector(2, 9, 1)
v3 = v1 + v2
print(v3)