Vector Class Redux


In [1]:
from vector2d_v0 import Vector2d

In [2]:
v1 = Vector2d(3, 4)
print(v1.x, v1.y)


3.0 4.0

In [3]:
x, y = v1

In [4]:
x, y


Out[4]:
(3.0, 4.0)

In [5]:
v1


Out[5]:
Vector2d(3.0, 4.0)

In [6]:
v1_clone = eval(repr(v1))
v1 == v1_clone


Out[6]:
True

In [7]:
print(v1)


(3.0, 4.0)

In [8]:
octets = bytes(v1)

In [9]:
octets


Out[9]:
b'd\x00\x00\x00\x00\x00\x00\x08@\x00\x00\x00\x00\x00\x00\x10@'

In [10]:
abs(v1)


Out[10]:
5.0

In [11]:
bool(v1), bool(Vector2d(0, 0))


Out[11]:
(True, False)

classmethod Versus staticmethod


In [1]:
class Demo:
    @classmethod
    def klassmeth(*args):
        return args
    @staticmethod
    def statmeth(*args):
        return args

In [2]:
Demo.klassmeth()


Out[2]:
(__main__.Demo,)

In [5]:
Demo.klassmeth('spam')


Out[5]:
(__main__.Demo, 'spam')

In [3]:
Demo.statmeth()


Out[3]:
()

In [4]:
Demo.statmeth('spam')


Out[4]:
('spam',)

Formatted Displays


In [6]:
brl = 1/2.43

In [7]:
brl


Out[7]:
0.4115226337448559

In [8]:
format(brl, '0.4f')


Out[8]:
'0.4115'

In [23]:
'1 BRL = {rate:0.2f} USD'.format(rate=brl)


Out[23]:
'1 BRL = 0.41 USD'

In [24]:
format(42, 'b')


Out[24]:
'101010'

In [25]:
format(2/3, '.1%')


Out[25]:
'66.7%'

In [ ]:
from datetime import datetime

In [28]:
now = datetime.now()
format(now, '%H:%M:%S')


Out[28]:
'21:21:38'

In [29]:
"It's now {:%I:%M %p}".format(now)


Out[29]:
"It's now 09:21 PM"

In [13]:
import vector2d_v1

In [14]:
from vector2d_v1 import Vector2d

In [2]:
v1 = Vector2d(3, 4)
format(v1)


Out[2]:
'(3.0, 4.0)'

In [3]:
format(v1, '.3f')


Out[3]:
'(3.000, 4.000)'

In [15]:
format(Vector2d(1, 1), 'p')


Out[15]:
'<1.0, 1.0>'

In [5]:
format(Vector2d(1, 1), '.3ep')


Out[5]:
'<1.000e+00, 1.000e+00>'

In [6]:
format(Vector2d(1, 1), '0.5fp')


Out[6]:
'<1.00000, 1.00000>'

In [7]:
format(Vector2d(1, 1), '0.5f')


Out[7]:
'(1.00000, 1.00000)'

A Hashable Vector2d


In [1]:
from vector2d_v1 import Vector2d

In [2]:
v1 = Vector2d(3, 4)

In [3]:
hash(v1)


---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-3-a179f9202156> in <module>()
----> 1 hash(v1)

TypeError: unhashable type: 'Vector2d'

In [4]:
v1.x, v1.y


Out[4]:
(3.0, 4.0)

In [5]:
v1.x = 7

In [6]:
v1.x, v1.y


Out[6]:
(7, 4.0)

In [8]:
import vector2d_v3 as v2d3

In [10]:
v1 = v2d3.Vector2d(3, 4)
v2 = v2d3.Vector2d(3.1, 4.2)
hash(v1), hash(v2)


Out[10]:
(7, 384307168202284039)

In [11]:
set([v1, v2])


Out[11]:
{Vector2d(3.1, 4.2), Vector2d(3.0, 4.0)}

In [12]:
v1_clone = v2d3.Vector2d.frombytes(bytes(v1))

In [13]:
v1_clone


Out[13]:
Vector2d(3.0, 4.0)

In [14]:
v1 == v1_clone


Out[14]:
True

Private and "Protected" Attributes in Python


In [15]:
v1 = v2d3.Vector2d(3, 4)
v1.__dict__


Out[15]:
{'_Vector2d__x': 3.0, '_Vector2d__y': 4.0}

In [16]:
v1._Vector2d__x


Out[16]:
3.0

Saving Space with the slots Class Attribute


In [ ]: