简阶
这里的内容全部来自《python3 面向对象编程》,我将会把里面重要的知识点和案例代码贴出来。
持续更新…
第1章 面向对象设计
第2章 Python 对象
第3章 对象相似时
第4章 异常捕获
第5章 何时使用面向对象编程
第6章 Python 数据结构
第7章 Python 面向对象的捷径
python 上下文管理器 (with 语法)
class StringJoiner(list):
def __enter__(self):
return self
def __exit__(self, exc_type, exc_val, exc_tb):
self.result = "".join(self)
import random, string
with StringJoiner() as joiner:
for i in range(15):
joiner.append(random.choice(string.ascii_letters))
print(joiner.result)
// 输出结果 >> LkWmGMSUxicWFzB
第8章 字符串与序列化
字符串格式化
# 字符串格式化
template = 'Hello {}, you are currently {}.'
print(template.format('Dusty', 'writing'))
template = 'Hello {0}, you are {1}. Your name is {0}.'
print(template.format('Dusty', 'writing',))
# 跳过花括号
template = '''
public class {0} {{
public static void main(String[] args) {{
System.out.println("{1}");
}}
}}
'''
print(template.format('MyClass', 'print(\\"hello world\\")'))
# 关键字参数
template = """
From: <{from_email}>
To: <{to_email}>
subject: {subject}
{message}"""
print(template.format(
from_email="a@example.com",
to_email="b@example.com",
message="Here's some mail for you. "
" Hope you enjoy the message!",
subject="You have mail!"
))
print("{} {label} {}".format("x", "y", label="z"))
# 字典参数 python2.7 不支持
phonebook = {'Beth': '9102', 'Alice': '2341', 'Cecil': '3258'}
print("Cecil's phone number is {Cecil}.".format_map(phonebook))
第9章 迭代器模式
第10章 Python 设计模式I
Python的装饰器模式
方法log_calls 是装饰器,test_* 是被装饰的方法
import time
def log_calls(func):
def wrapper(*args, **kwargs):
now = time.time()
print("Calling {0} with {1} and {2}".format(
func.__name__, args, kwargs
))
return_value = func(*args, **kwargs)
print("Executed {0} in {1}ms".format(
func.__name__, time.time() - now
))
return return_value
return wrapper
def test_1(a, b, c):
print("\ttest_1 called")
def test_2(a, b):
print("\ttest_2 called")
def test_3(a, b):
print("\ttest_3 called")
time.sleep(1)
test_1 = log_calls(test_1)
test_2 = log_calls(test_2)
test_3 = log_calls(test_3)
test_1(1, 2, 3)
test_2(4, b=5)
test_3(6, 7)
输出结果:
Calling test_1 with (1, 2, 3) and {}
test_1 called
Executed test_1 in 7.82012939453125e-05ms
Calling test_2 with (4,) and {‘b’: 5}
test_2 called
Executed test_2 in 1.6927719116210938e-05ms
Calling test_3 with (6, 7) and {}
test_3 called
Executed test_3 in 1.0050618648529053ms
另一种语法
@log_calls
def test_1(a, b, c):
print("\ttest_1 called")
test_1(1, 2, 3)
观察者模式
class Inventory:
def __init__(self):
self.observers = []
self._product = None
self._quantity = 0
def attach(self, observer):
self.observers.append(observer)
@property
def product(self):
return self._product
@product.setter
def product(self, value):
self._product = value
self._update_observers()
@property
def quantity(self):
return self._quantity
@quantity.setter
def quantity(self, value):
self._quantity = value
self._update_observers()
def _update_observers(self):
for observer in self.observers:
observer()
class ConsoleObserver:
def __init__(self, inventory):
self.inventory = inventory
def __call__(self):
print(self.inventory.product)
print(self.inventory.quantity)
if __name__ == '__main__':
i = Inventory()
c = ConsoleObserver(i)
i.attach(c)
i.product = 'widget'
i.quantity = 5
c1 = ConsoleObserver(i)
i.attach(c1)
i.product = 'Gadget'
第11章 Python 设计模式II
第12章 测试面向对象程序
第13章 并发