1 · fluentpython/example-code@62e6cb1

This repository was archived by the owner on Dec 2, 2021. It is now read-only.

File tree

2 files changed

lines changed

2 files changed

lines changed

Original file line numberDiff line numberDiff line change

@@ -1,4 +1,5 @@

11

import collections

2+

from random import choice

23
34

Card = collections.namedtuple('Card', ['rank', 'suit'])

45

@@ -15,3 +16,13 @@ def __len__(self):

1516
1617

def __getitem__(self, position):

1718

return self._cards[position]

19+
20+

if __name__ == '__main__':

21+

beer_card = Card('7', 'diamonds')

22+

print(beer_card)

23+
24+
25+

deck = FrenchDeck()

26+

print(len(deck))

27+

print(deck[0])

28+

print(choice(deck))

Original file line numberDiff line numberDiff line change

@@ -1,11 +1,13 @@

11

from math import hypot

22
3+
34

class Vector:

45
56

def __init__(self, x=0, y=0):

67

self.x = x

78

self.y = y

89
10+

"""类似 java 的 toString 方法"""

911

def __repr__(self):

1012

return 'Vector(%r, %r)' % (self.x, self.y)

1113

@@ -20,5 +22,13 @@ def __add__(self, other):

2022

y = self.y + other.y

2123

return Vector(x, y)

2224
25+
26+

"""标量乘法?"""

2327

def __mul__(self, scalar):

2428

return Vector(self.x * scalar, self.y * scalar)

29+
30+
31+

if __name__ == '__main__':

32+

v1 = Vector(2, 4)

33+

v2 = Vector(2, 1)

34+

print(v1 + v2)