Python基础

参考索引[1, 2]

class [3]

  • python所有对象都是类
    • function也是类,可以set_attribute 或者 get_attribute
    • class TypeA 的声明,会生成一个meteclass(type)的对象,该TypeA不仅是类也是对象。TypeA()会调用metaclass 的 __call__ 方法。
    • TypeA() 的调用顺序是__new__, __init__
    • 动态生成类:
      Foo = type(
          'Foo',
          (),
          {
              'attr': 100,
              'attr_val': f
          }
      )
      

Decorator [4]

  • 类装饰器:__call__里写。
  • functools.cache python 自带的缓存装饰器。[5]

内存管理 [6]

  • 遍历的是容器对象,并且不根据引用关系遍历,而是根据自己的链表遍历。
  • 接下来第二遍才是根据引用关系遍历

迭代器和生成器 [7]

  • 迭代器:实现了迭代接口的对象。 __iter____next____iter__一般返回self__next__要自行保存迭代的位置。结束通过抛出StopIteration的错误。
  • 生成器函数: def 定义, yield返回结果
    • 生成器是 Iterable(可迭代对象), 不是Iterator (迭代器)
  • 生成器表达式: (i for i in range(10)) ,返回生成器
  • 可以通过 iter() 函数包装,将生成器变成迭代器,从而可以使用next()方法。
  • for 会自动将生成器包装成迭代器。[8]

List 实现和应用[9]

  • 连续数组
  • 插入和删除都是O(n)的, append, pop(-1)为O(1)
  • get slice[x:y] O(k)
    del slice O(n)
    set slice O(n+k)
  • Slice with Negative Step Size: start 应该是从后面开始的,print(L[6:1:-2]) [10]
  • Insert Multiple List Items:Simply specify a zero-length slice[10]
    # Insert at the start
    L = ['a', 'b', 'c']
    L[:0] = [1, 2, 3]
    print(L)
    # Prints [1, 2, 3, 'a', 'b', 'c']
    # Insert at the end
    L = ['a', 'b', 'c']
    L[len(L):] = [1, 2, 3]
    print(L)
    # Prints ['a', 'b', 'c', 1, 2, 3]
    # Insert in the middle
    # You can insert items into the middle of list by keeping both the start and stop indices of the slice same.
    L = ['a', 'b', 'c']
    L[1:1] = [1, 2, 3]
    print(L)
    # Prints ['a', 1, 2, 3, 'b', 'c']
    
  • Delete Multiple List Items:L[1:5] = [] or del L[1:5] [10]

继承

类方法

  • @classmethod
    def car_count(cls):     # 类方法,只访问类变量
        print(f"我有{cls.car_num}辆车")
    

    [11]

编程规范

  • 不要用检查长度的方式来判断字符串、列表等是否为None或者没有元素,应该用if not x这样的写法来检查它。
  • 如果有多个import语句,应该将其分为三部分,从上到下分别是Python标准模块、第三方模块和自定义模块,每个部分内部应该按照模块名称的字母表顺序来排列。

magic method

  • 通过定义类似 __slot__ = ('__value', ),不允许在类内创建新值 [12]

基础函数

  • defaultdict: 返回函数默认的值 [13]
  • deque: list-like,在两端append和pop 是O(1)的 [14]
  • nametuple: 返回的是一个类,可以继承,然后定义方法。 Card = namedtuple('Card', ('suite', 'face'))

Exception [15]

try:
       # Some Code.... 

except:
       # optional block
       # Handling of exception (if required)

else:
       # execute if no exception

finally:
      # Some code .....(always executed)

反射 [16]

参考

Written on April 14, 2022