Appearance
python 核心技术
一切皆对象
- object 是所有类(含 type, 但不含 object)的基类
- 所有类(含 object 与 type)均是 type 类的实例
py
class Foo:
pass
class Bar(Foo):
pass
foo = Foo()
age = 18
print(f"整型常量的类型: {type(18)}") # noqa: UP003 👉 <class 'int'>
print(f"整数类型的类型: {type(int)}") # 👉 <class 'type'>
print(f"整型变量的类型: {type(age)}") # 👉 <class 'int'>
print(f"Foo实例的类型: {type(foo)}") # 👉 <class '__main__.Foo'>
print(f"Foo自身的类型: {type(Foo)}") # 👉 <class 'type'>
print(f"type类的类型: {type(type)}") # 👉 <class 'type'>
print(f"object的类型: {type(object)}") # 👉 <class 'type'>
print(f"整数类型的父类: {int.__bases__}") # 👉 (<class 'object'>,)
print(f"Foo自身的父类: {Foo.__bases__}") # 👉 (<class 'object'>,)
print(f"Bar自身的父类: {Bar.__bases__}") # 👉 (<class '__main__.Foo'>,)
print(f"type类的父类: {type.__bases__}") # 👉 (<class 'object'>,)
print(f"object的父类: {object.__bases__}") # 👉 ()
print(f"type 是 type 的实例: {isinstance(type, type)}") # 👉 True
print(f"object 是 type 的实例: {isinstance(object, type)}") # 👉 True
魔法函数
__getitem__
py
class Foo:
def __init__(self):
self.lst = [1, 2, 3, 4]
def __getitem__(self, item):
return self.lst[item]
foo = Foo()
for f in foo: # __getitem__
print(f)
# 👆 等价于 👇
for f in foo.lst:
print(f)
print(foo[::2]) # 支持切片 👉 [1, 3]
__repr__ 与 __str__
- __str__: 用于生成可读性强的字符串, 适合最终用户, 通常用于 print() 函数和用户界面
- __repr__: 用于生成精确的字符串, 适合调试和开发, 通常用于 repr() 函数和调试工具
- 如果没有定义 __str__ 方法, Python 会默认使用 __repr__ 方法
py
class Foo:
def __str__(self):
return "i am foo"
def __repr__(self):
return "I AM FOO"
foo = Foo()
print(foo) # 👉 i am foo
print(repr(foo)) # 👉 I AM FOO
__getattr__ 与 __getattribute__
- __getattr__: 找不到属性时调用
- __getattribute__: 任何属性都会走这个方法, 找不到时抛出
AttributeError
后会调用 __getattr__
py
class Foo:
def __getattr__(self, item):
return "i am foo"
def __getattribute__(self, item):
print("call", end=": ")
raise AttributeError
foo = Foo()
print(foo.unknown) # 未定义属性 👉 call: i am foo
多线程
- Queue
- Lock
- RLock
- Condition
- Semaphore
py
import threading
import time
from concurrent.futures import ThreadPoolExecutor
def test(func):
print(f"==== {func.__doc__} ====")
start = time.time()
func()
print(f"tasks done :{time.time() - start}")
return lambda: None
def run(id_):
print(f"task{id_}: start")
time.sleep(1)
print(f"task{id_}: end")
@test
def simple():
"""线程"""
tasks01 = []
for _ in range(2):
task = threading.Thread(target=run, args=(_,))
tasks01.append(task)
task.start()
for task in tasks01:
task.join()
@test
def pool():
"""线程池"""
with ThreadPoolExecutor(max_workers=2) as executor:
# from concurrent.futures import wait
# wait([executor.submit(run, _) for _ in range(2)])
# from concurrent.futures import as_completed
# list(as_completed([executor.submit(run, _) for _ in range(2)]))
for _ in range(2):
executor.submit(run, _)
协程
py
async def func1():
print("func")
return 1
async def main1():
r = await func1()
print("main")
return r
m = main1()
try:
m.send(None)
except StopIteration as e:
print(e.value) # 👉 1
def func2():
print("func2")
r = yield
print(r)
return 2
def main2():
r = yield from func2()
print("main2")
return r
m = main2()
try:
m.send(None)
m.send("msg to func2")
except StopIteration as e:
print(e.value) # 👉 2