class Complex:
def __init__(self, realpart, imagpart):
self.r = realpart
self.i = imagpart
x = Complex(3.0, -4.5)
x.r, x.i
(3.0, -4.5)
class Pet:
learnt_tricks = []
def __init__(self, name):
self.name = name
def learn_trick(self, trick):
self.learnt_tricks.append(trick)
d = Pet('Amao')
e = Pet('Ago')
d.learn_trick('roll')
e.learn_trick('play')
d.learnt_tricks
['roll', 'play']
class A:
def foo(self):
print("in A::foo")
class B(A):
pass
b = B()
b.foo()
in A::foo
class A:
def foo(self):
print("in A::foo")
class B(A):
def foo(self):
print("in B::foo")
b = B()
b.foo()
isinstance(b, B)
isinstance(b, A)
in B::foo
True
class A:
def foo(self):
print("in A::foo")
class B(A):
def foo(self):
print("in B::foo")
class C:
def foo(self):
print("not subclass of A/B")
def test_class(a):
a.foo()
a = A()
b = B()
c = C()
test_class(a)
test_class(b)
test_class(c)
in A::foo in B::foo not subclass of A/B
函数式特性
lambda演算
inc = lambda x: x + 1
add = lambda x, y: x + y
inc(5)
add(10, 20)
# 注意:Python的lambda表达式不能换行
30
闭包
def outer():
count = 0
def inner():
nonlocal count
count += 1
return count
return inner
counter = outer()
counter()
1
counter()
2
偏函数
from functools import partial
def multiply(x, y):
return x * y
double = partial(multiply, 2)
triple = partial(multiply, 3)
double
functools.partial(<function multiply at 0x000001945C208790>, 2)
type(double)
functools.partial
double(5)
10
triple(20)
60
列表推导
[i * 2 for i in range(10)]
[i * 2 for i in range(10) if i % 2 == 0]
colours = ["红", "绿", "黄", "蓝"]
things = ["房子", "车", "树"]
combined = [(x,y) for x in colours for y in things]
combined
[('红', '房子'), ('红', '车'), ('红', '树'), ('绿', '房子'), ('绿', '车'), ('绿', '树'), ('黄', '房子'), ('黄', '车'), ('黄', '树'), ('蓝', '房子'), ('蓝', '车'), ('蓝', '树')]
元组
t = 12345, 54321, 'hello!'
t
(12345, 54321, 'hello!')
# Tuples may be nested:
u = t, (1, 2, 3, 4, 5)
u
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
# Tuples are immutable:
try:
t[0] = 88888
except TypeError as e:
print(e)
'tuple' object does not support item assignment
# but they can contain mutable objects:
v = ([1, 2, 3], [3, 2, 1])
v[0][1] = 3
v
([1, 3, 3], [3, 2, 1])
empty = ()
singleton = 'hello', # <-- 末尾逗号
len(empty)
0
len(singleton)
1
字典
tel = {'张三': 123, '周五': 445}
tel['李四'] = 412
tel
{'张三': 123, '周五': 445, '李四': 412}
tel['张三']
del tel['李四']
tel['王六'] = 4127
tel
{'张三': 123, '周五': 445, '王六': 4127}
list(tel.keys())
sorted(tel.keys())
'张三' in tel
True
'张三' not in tel
False
x = {}
x[(1, 2, 3)] = 4
x
{(1, 2, 3): 4}
try:
x[(1, 2, [3, 4])] = 5
except TypeError as e:
print(e)
unhashable type: 'list'
dict([('张三', 413),
('李四', 412),
('周五', 409)])
{'张三': 413, '李四': 412, '周五': 409}
{x: x**2 for x in (2, 4, 6)}
{2: 4, 4: 16, 6: 36}
dict(张三=413, 李四=412, 周五=409)
{'张三': 413, '李四': 412, '周五': 409}
集合
course = {'math', 'english', 'physical education', 'math', 'english'}
print(course) # show that duplicates have been removed
{'physical education', 'math', 'english'}
'math' in course # fast membership testing
True
'chemistry' in course
False
a = set('banana')
b = set('carrot')
a - b
{'b', 'n'}
a | b
{'a', 'b', 'c', 'n', 'o', 'r', 't'}
a & b
{'a'}
a ^ b
{'b', 'c', 'n', 'o', 'r', 't'}
a = {x for x in 'abracadabra' if x not in 'abc'}
a
{'d', 'r'}