What Does It Take To Be An Expert At Python?
链接:https://www.youtube.com/watch?v=7lmCu8wz8ro
Three core patterns of object orientation
protocol view of python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
| # some behaviour that I want to implement -> write some __function __
# ----------------------------------------------------------------------------------
# python data model documentation https://docs.python.org/3/reference/datamodel.html
# top-level function or top-level syntax -> corresponding __
# x + y -> __add__
# init x -> __init__
# repr(x) -> __repr__
# x() -> __call__
class Polynomial:
def __init__(self, *coeffs):
self.coeffs = coeffs
def __repr__(self):
return 'Polynomial(*{!r})'.format(self.coeffs)
def __add__(self, other):
return Polynomial(*(x + y for x, y in zip(self.coeffs, other.coeffs)))
def __len__(self):
return len(self.coeffs)
def __call__(self):
pass
# 交互式运行:python -i xx.py
|
build-in inheritance protocol and how it works where you go on a python object to look for things
caveats around how object orientation of python works
User view
1
2
3
4
5
6
| # library.py
# metaclass
class Base:
def foo(self):
return 'foo'
|
1
2
3
4
5
6
7
| # user.py
from library import Base
assert hasattr(Base, 'foo'), "you broke it" # 判定是否存在某个内置方法
class Derived(Base):
def bar(self):
return self.foo
|
Library view
1
2
3
4
5
6
7
8
9
10
11
| # library.py
class BaseMeta(type): # 继承了type的类型,判断开发者的类中是否存在broken class
def __new__(cls, name, base, body):
if not 'bar' in body:
raise TypeError("bad user class")
return super().__new__(cls, name, name, bases, body)
class Base(metaclass=BaseMeta):
def foo(self):
return self.bar()
|
1
2
3
4
5
6
| # user.py
from library import Base
class Derived(Base):
def bar(self):
return 'bar'
|
decorator
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
| # dec.py
from time import time
def timer(func):
def wrapper(*args, **kwargs): #wrapper
before = time()
rv = func(*args, **kwargs)
after = time()
print('elapsed', after - before)
return rv
return wrapper
@timer
def add(x, y=10):
return x+y
# add =timer(add(1, 2))
|
generators
1
2
3
4
5
| # gen.py
# top-level syntax, fuction -> underscore method
def a
|