AI智能
改变未来

流畅的Python-2021:1.数据模型


第一章(下方资料)

https://github.com/fluentpython/example-code-2e/tree/master/01-data-model

Python风格的纸牌

"""第一章:1. 数据模型https://docs.python.org/zh-cn/3/reference/datamodel.html"""# 容器数据类型import collectionsCard = collections.namedtuple(\'Card\', [\'rank\', \'suit\'])class FrenchDeck:ranks = [str(n) for n in range(2, 11)] + list(\'JQKA\')suits = \'spades diamonds clubs hearts\'.split()def __init__(self):# 列表推导式-> 外层for循环 self.suits(花色)#               -> 内层for循环 self.ranks(牌面)self._cards = [Card(rank, suit) for suit in self.suitsfor rank in self.ranks]def __len__(self):"""实现之后,对象可以len()"""return len(self._cards)def __getitem__(self, position):"""实现之后,对象可以切片 、 下标取值、课迭代"""return self._cards[position]@propertydef cards(self):"""将方法变成属性"""return self._cardsif __name__ == \'__main__\':fd = FrenchDeck()print(fd.cards)print(len(fd))  # 类实现了 __len__ 函数print(fd[::-1]) # 实现了 __getitem__ 函数

自定义向量类

"""vector2d.py: a simplistic class demonstrating some special methodsIt is simplistic for didactic reasons. It lacks proper error handling,especially in the ``__add__`` and ``__mul__`` methods.This example is greatly expanded later in the book.Addition::>>> v1 = Vector(2, 4)>>> v2 = Vector(2, 1)>>> v1 + v2Vector(4, 5)Absolute value::>>> v = Vector(3, 4)>>> abs(v)5.0Scalar multiplication::>>> v * 3Vector(9, 12)>>> abs(v * 3)15.0"""import mathclass Vector:def __init__(self, x=0, y=0):self.x = xself.y = ydef __repr__(self): # print时找不到__str__ 才会进这里, 控制台的时候调用""" 把对象 已字符串内容形式返回转换标志:’!S’调用 str ()的值,’!R’调用 repr ()和’!A’调用 ascii ()。!r => 首先对参数调用 repr()!s => 首先对参数调用 str()!a => 首先对参数调用 ascii():return:"""return f\'Vector({self.x!r}, {self.y!r})\'def __str__(self):  # print的时候调用return "demo"def __abs__(self):  # 对象可用 abs()# math.hypot 多维计算return math.hypot(self.x, self.y)def __len__(self):return Falsedef __bool__(self):  # 可使用 bool(), 当找不到__bool__时 会去找 __len__方法return bool(abs(self))def __add__(self, other):  # 对象 +x = self.x + other.xy = self.y + other.yreturn Vector(x, y)def __mul__(self, scalar):  # 对象 *return Vector(self.x * scalar, self.y * scalar)if __name__ == \'__main__\':print(Vector())print(bool(Vector()))
赞(0) 打赏
未经允许不得转载:爱站程序员基地 » 流畅的Python-2021:1.数据模型