In [26]:
class Complex:
    def __init__(self, realpart, imagpart):
        self.r = realpart
        self.i = imagpart
x = Complex(3.0, -4.5)
x.r, x.i
Out[26]:
(3.0, -4.5)
In [27]:
class Pet:

    learnt_tricks = []

    def __init__(self, name):
        self.name = name

    def learn_trick(self, trick):
        self.learnt_tricks.append(trick)
In [28]:
d = Pet('Amao')
e = Pet('Ago')
d.learn_trick('roll')
e.learn_trick('play')
d.learnt_tricks               
Out[28]:
['roll', 'play']
In [29]:
class A:
    def foo(self):
        print("in A::foo")

class B(A):
    pass

b = B()
b.foo()
in A::foo
In [30]:
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
Out[30]:
True
In [31]:
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演算

In [32]:
inc = lambda x: x + 1

add = lambda x, y: x + y

inc(5)
add(10, 20)

# 注意:Python的lambda表达式不能换行
Out[32]:
30

闭包

In [33]:
def outer():
    count = 0
    def inner():
        nonlocal count
        count += 1
        return count
    return inner
In [34]:
counter = outer()
In [35]:
counter()
Out[35]:
1
In [36]:
counter()
Out[36]:
2

偏函数

In [37]:
from functools import partial
def multiply(x, y):
    return x * y

double = partial(multiply, 2)
triple = partial(multiply, 3)
In [38]:
double
Out[38]:
functools.partial(<function multiply at 0x000001945C208790>, 2)
In [39]:
type(double)
Out[39]:
functools.partial
In [40]:
double(5)
Out[40]:
10
In [41]:
triple(20)
Out[41]:
60

列表推导

In [42]:
[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]
In [43]:
combined
Out[43]:
[('红', '房子'),
 ('红', '车'),
 ('红', '树'),
 ('绿', '房子'),
 ('绿', '车'),
 ('绿', '树'),
 ('黄', '房子'),
 ('黄', '车'),
 ('黄', '树'),
 ('蓝', '房子'),
 ('蓝', '车'),
 ('蓝', '树')]

元组

In [44]:
t = 12345, 54321, 'hello!'
In [45]:
t
Out[45]:
(12345, 54321, 'hello!')
In [46]:
# Tuples may be nested:
u = t, (1, 2, 3, 4, 5)
u
Out[46]:
((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
In [47]:
# Tuples are immutable:
try:
    t[0] = 88888
except TypeError as e:
    print(e)
'tuple' object does not support item assignment
In [48]:
# but they can contain mutable objects:
v = ([1, 2, 3], [3, 2, 1])
v[0][1] = 3
In [49]:
v
Out[49]:
([1, 3, 3], [3, 2, 1])
In [50]:
empty = ()
singleton = 'hello',    # <-- 末尾逗号
len(empty)
Out[50]:
0
In [51]:
len(singleton)
Out[51]:
1

字典

In [52]:
tel = {'张三': 123, '周五': 445}
tel['李四'] = 412
tel
Out[52]:
{'张三': 123, '周五': 445, '李四': 412}
In [53]:
tel['张三']
del tel['李四']
tel['王六'] = 4127
tel
Out[53]:
{'张三': 123, '周五': 445, '王六': 4127}
In [54]:
list(tel.keys())
sorted(tel.keys())
'张三' in tel
Out[54]:
True
In [55]:
'张三' not in tel
Out[55]:
False
In [56]:
x = {}
x[(1, 2, 3)] = 4
x
Out[56]:
{(1, 2, 3): 4}
In [57]:
try:
    x[(1, 2, [3, 4])] = 5
except TypeError as e:
    print(e)
unhashable type: 'list'
In [58]:
 dict([('张三', 413), 
          ('李四', 412), 
          ('周五', 409)])
Out[58]:
{'张三': 413, '李四': 412, '周五': 409}
In [59]:
{x: x**2 for x in (2, 4, 6)}
Out[59]:
{2: 4, 4: 16, 6: 36}
In [60]:
dict(张三=413, 李四=412, 周五=409)
Out[60]:
{'张三': 413, '李四': 412, '周五': 409}

集合

In [61]:
course = {'math', 'english', 'physical education', 'math', 'english'}
print(course)                      # show that duplicates have been removed
{'physical education', 'math', 'english'}
In [62]:
'math' in course                 # fast membership testing
Out[62]:
True
In [63]:
'chemistry' in course
Out[63]:
False
In [64]:
a = set('banana')
b = set('carrot')
In [65]:
a - b 
Out[65]:
{'b', 'n'}
In [66]:
a | b                             
Out[66]:
{'a', 'b', 'c', 'n', 'o', 'r', 't'}
In [67]:
a & b                          
Out[67]:
{'a'}
In [68]:
a ^ b                          
Out[68]:
{'b', 'c', 'n', 'o', 'r', 't'}
In [69]:
a = {x for x in 'abracadabra' if x not in 'abc'}
In [70]:
a
Out[70]:
{'d', 'r'}
In [ ]: