python常用小技巧整理的一些文件

it2023-02-05  77

文章目录

1. _ _ new _ _:2. _ _ init _ _:__set__:__get__:析构__del__lambda 匿名函数断言getattr 参考

1. _ _ new _ _:

我们首先得从__new__(cls[,…])的参数说说起,__new__方法的第一个参数是这个类,而其余的参数会在调用成功后全部传递给__init__方法初始化,

class A: pass class B(A): def __new__(cls): print("__new__方法被执行") return super().__new__(cls) # 注意这里,需要初始化 def __init__(self): print("__init__方法被执行") b = B()

输出

__new__方法被执行 __init__方法被执行

我们平时用__init__做初始化就好,什么时候用到__new__呢,看一下项目中是怎么用的,这里主要是涉及到了对象的操作,可以有效地防止反复创建对象,

class Logger: def __new__(cls, app_name: str, log_path: str, *args, **kwargs): if app_name not in cls.__instance: cls.__instance[app_name] = super().__new__(cls) return cls.__instance[app_name]

2. _ _ init _ _:

set:
get:
析构__del__
lambda 匿名函数
lambda x: x**2 #等价于下面 def find_a_name(x): return x**2 l = map(find_a_name, [1, 2, 3]) for i in l: print(i) l = map(lambda x: x**2, [1, 2, 3]) for i in l: print(i)
断言
log_path = 2 assert(type(log_path) is str), f'传入的日志路径必须为字符串,当前传入的路径为:{log_path},类型为:{type(log_path)}'

报错输出

Traceback (most recent call last): File "/usr/local/pycharm-2020.1.1/plugins/python/helpers/pydev/_pydevd_bundle/pydevd_exec2.py", line 3, in Exec exec(exp, global_vars, local_vars) File "<input>", line 1, in <module> AssertionError: 传入的日志路径必须为字符串,当前传入的路径为:2 ,类型为:<class 'int'>
getattr

参考

[1] 通俗的讲解Python中的__new__()方法[2] Wikipedia
最新回复(0)