流畅的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 collections

Card = 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.suits
                                        for rank in self.ranks]

    def __len__(self):
        """实现之后,对象可以len()"""
        return len(self._cards)

    def __getitem__(self, position):
        """实现之后,对象可以切片 、 下标取值、课迭代"""
        return self._cards[position]

    @property
    def cards(self):
        """将方法变成属性"""
        return self._cards


if __name__ == '__main__':
    fd = FrenchDeck()
    print(fd.cards)
    print(len(fd))  # 类实现了 __len__ 函数
    print(fd[::-1]) # 实现了 __getitem__ 函数

自定义向量类

"""
vector2d.py: a simplistic class demonstrating some special methods

It 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 + v2
    Vector(4, 5)

Absolute value::

    >>> v = Vector(3, 4)
    >>> abs(v)
    5.0

Scalar multiplication::

    >>> v * 3
    Vector(9, 12)
    >>> abs(v * 3)
    15.0

"""


import math

class Vector:

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

    def __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 False

    def __bool__(self):  # 可使用 bool(), 当找不到__bool__时 会去找 __len__方法
        return bool(abs(self))

    def __add__(self, other):  # 对象 +
        x = self.x + other.x
        y = self.y + other.y
        return Vector(x, y)

    def __mul__(self, scalar):  # 对象 *
        return Vector(self.x * scalar, self.y * scalar)


if __name__ == '__main__':
    print(Vector())
    print(bool(Vector()))
作者:zy7y
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文链接,否则保留追究法律责任的权利。
原文地址:https://www.cnblogs.com/zy7y/p/15108037.html