Fluent Python笔记0x01

划了两周水……

p8

  • special methods是由Python解释器调用,不需要你来调用(虽然也可以亲自调用)。
  • 对于内置类型如liststrbytearray等来说,调用len()则是由CPython直接返回PyVarObject(C的struct)中关于长度的变量,这比调用__len__要快很多。

p10

  • 例子1-2:

from math import hypot


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

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

    def __abs__(self):
        return hypot(self.x, self.y)

    def __bool__(self):
        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, other):
        return Vector(self.x * other, self.y * other)

p11

简单来说__repr__是为了保证无歧义,而__str__是为了提供可读性。在Python提供的类中,使用__repr__返回的结果都是格式化的数据,是符合Python语法的;__str__则是面向一般用户,提供可读性,但不保证无歧义,例如int型的3和str的3满足:

str(3) == str('3')

p12

  • 关于运算符:例1-2中声明的__add____mul__是针对+*的重载。注意这里乘法参数顺序必须为向量在前数在后。
  • 布尔值:在Python中,任何对象都有布尔值。如果对象未声明__bool____len__,则其布尔值恒为True。如果声明了__bool__bool()会使用其返回值。如果没有声明__bool__而声明了__len__则会使用len()的返回值,为0则为False,否则为True
  • 有关例1-2中Vector.__bool__一个更加便捷的声明:

def __bool__(self):
    return bool(self.x or self.y)

这样可以避免使用abs()

Author: SinLapis
Link: http://sinlapis.github.io/2017/07/19/FluentPython笔记0x01/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.