Python常用特性

字符串格式化

Python中的f字符串、format()内置函数、str.format()方法中都接受format_spec作为参数。

f字符串中包含一种特殊的以开闭花括号(‘{‘, ‘}‘)为界的replacement field,形如{field_name:format_spec}

在format_spec中使用的记号称之为Format Specification Mini-Language。

用户自定义类可以实现__format__方法来自定义自己的Format Specification Mini-Language,object类中的默认实现是返回str(my_object)

可哈希类(Hashable Type)

从语法上讲,在类的定义中必须实现以下2个方法:

  • __eq__(self, other: object)
  • __hash__(self)

从语义上讲,类的定义必须满足以下条件:

  • 类的实例在进行相等性比较的时候,相等的实例必须拥有相等的哈希值
  • 类的实例不可变

序列类(Sequence Type)

切片(Slicing)

用户自定义类支持切片的必要条件是实现__getitem__魔法方法,语义上也要满足。当执行切片时,__getitem__的入参类型为slice,且它是Python的内置类型。

slice类型除了大家熟知的startstopstride外,还有一个鲜为人知的方法,indices,官方文档说明如下:

S.indices(len) -> (start, stop, stride)

Assuming a sequence of length len, calculate the start and stop
indices, and the stride length of the extended slice described by
S. Out of bounds indices are clipped in a manner consistent with the
handling of normal slices.

说白了,某个slice中的三个关键属性:startstopstride,有可能缺省,有可能为负数,indices的作用就是根据序列的长度len,把它们补齐,或者重新计算,使得其“完美”适配长度为len的序列,比如原本stop属性的值大于len,那么新的stop会等于len,这个过程称之为归一化(Normalize)。

私有以及”保护”属性

  • 以双下划线(__)开头的属性称为私有属性,解释器会对其做”name mangle”,具体做法是在原有名字的基础上拼接单下划线类名的前缀,程序员可以通过__dict__属性查看。
  • 以单下划线(_)开头的属性称为“保护”属性,之所以要加引号是因为对于解释器来说,所谓的“保护”属性并没有什么不同,仅仅是程序员之间形成的一个约定而已

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *