• 主页
  • 相册
  • 随笔
  • 目录
  • 存档
Total 244
Search AboutMe

  • 主页
  • 相册
  • 随笔
  • 目录
  • 存档

Python厨书笔记-8

2020-02-08

1. 类与对象

2. 对象的字符串显示

  • __repr__()

    • 返回一个实例的代码表示形式
    • 内置的repr()函数返回这个字符串,跟我们使用交互式解释器显示的值是一样的
  • __str__()

    • 将实例转换为一个字符串
    • 使用 str() 或 print() 函数会输出这个字符串
    • 如果 __str__() 没有被定义,那么就会使用 __repr__() 来代替输出

3. 自定义字符串的格式化

  • format()重构

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    _formats = {
    'ymd' : '{d.year}-{d.month}-{d.day}',
    'mdy' : '{d.month}/{d.day}/{d.year}',
    'dmy' : '{d.day}/{d.month}/{d.year}'
    }

    class Date:
    def __init__(self, year, month, day):
    self.year = year
    self.month = month
    self.day = day

    def __format__(self, code):
    if code == '':
    code = 'ymd'
    fmt = _formats[code]
    return fmt.format(d=self)
    >>> d = Date(2012, 12, 21)
    >>> format(d)
    '2012-12-21'
    >>> format(d, 'mdy')
    '12/21/2012'
    >>> 'The date is {:ymd}'.format(d)
    'The date is 2012-12-21'
  • 关于冒号

    • {字段名!转换字段:格式说明符}
      1
      2
      3
      4
      print('{0:{1}}'.format(3.14159, '.  4f'))
      """
      3.1416
      """

4. 编写上下文管理器

  • 主要原理

    代码会放到 with 语句块中执行。 当出现 with 语句的时候,对象的 enter() 方法被触发, 它返回的值(如果有的话)会被赋值给 as 声明的变量。然后,with 语句块里面的代码开始执行。 最后,exit() 方法被触发进行清理工作。

5.

__slots__

当你定义 slots 后,Python就会为实例使用一种更加紧凑的内部表示。 实例通过一个很小的固定大小的数组来构建,而不是为每个实例定义一个字典,这跟元组或列表很类似。 在 slots 中列出的属性名在内部被映射到这个数组的指定小标上。 使用slots一个不好的地方就是我们不能再给实例添加新的属性了,只能使用在 slots 中定义的那些属性名

1
2
3
4
5
6
class Date:
__slots__ = ['year', 'month', > 'day']
def __init__(self, year, month, > day):
self.year = year
self.month = month
self.day = day

6. 在类中封装属性名

  • 双下划线
    • 这种属性无法通过继承被覆盖
1
2
3
4
5
6
7
8
class C(B):
def __init__(self):
super().__init__()
self.__private = 1 # Does not override B.__private

# Does not override B.__private_method()
def __private_method(self):
pass
  • 私有名称 __private 和 __private_method 被重命名为 _C__private和 _C__private_method
  • Cookbook
  • Program Language
  • Python
  • Cookbook
vscode快捷键
leetcode-1
  1. 1. 1. 类与对象
    1. 1.1. 2. 对象的字符串显示
    2. 1.2. 3. 自定义字符串的格式化
    3. 1.3. 4. 编写上下文管理器
    4. 1.4. 5.
    5. 1.5. 6. 在类中封装属性名
© 2024 何决云 载入天数...