
本文共 104416 字,大约阅读时间需要 348 分钟。
���������������
������������
������������������
���type()
������������������������
type(1)
int
type(1.0)
float
type('python')
str
type(True)
bool
type(None)
NoneType
type([])
list
type(())
tuple
type({})
dict
type(set())
set
���������������������������������������isinstance()
:
isinstance(1, int)
True
isinstance([1, 2, 3], list)
True
isinstance(('���������', 'https://www.cnblogs.com/iflyendless/'), tuple)
True
isinstance({}, dict)
True
isinstance({1,}, set)
True
isinstance()
���������������������������������������������������������������������
isinstance(3.14, (int, float))
True
���������isinstance(3.14, int) or isinstance(3.14, float)
���
isinstance(3.14, int) or isinstance(3.14, float)
True
id()
������������������������������������������������������������������CPython
���id()
������������������������������������������
id('���������')
4594512016
id(1)
4553398624
id([])
4593405440
������������4������������������:
num = -100if num >= 0: print(num)else: print(-num)
100
���Python���������������������������������������/
:
10 / 3
3.3333333333333335
/
���������������������������������������������������������������������������������������������
9 / 3
3.0
���������������������//
������������������������������������������������������������
10 // 3
3
������������������������������������//
������������������������������������������������������������������/
������������
������//
������������������������������������������Python������������������������������������������������������������������������
10 % 3
1
���������������������������10000000000
������������������0������������
Python������������������������_
������������������������10_000_000_000
���10000000000
���������������������������������������������������0xa1b2_c3d4
10_000_000_000 == 10000000000
True
0xa1b2_c3d4 == 0xa1b2c3d4
True
������������������������������10
���e
���������1.23x10^9
������1.23e9
���������12.3e8
���0.000012
������������1.2e-5
1.23e9 == 12.3e8
True
0.000012 == 1.2e-5
True
������������������and
���or
���not
���������
True and True
True
True and False
False
True or False
True
not 1 > 0
False
���������Python���������������������������None
���������
None
���������������0���������0���������������������None
���������������������������
���������������������������������������������_���������������������������������������
���Python������������=������������������������������������������������������������������������������������������������������������������������������������������
a = 123a
123
a = 'ABC'a
'ABC'
���������������������������������������������������������������
���������������������������������
���
������������(���������Java)���������������������������������������������������������������������������������������������������
a = 'ABC'b = aa = 'XYZ'print(b)print(a)
ABCXYZ
a = 'ABC'
Python������������������������������
- ���������������������������'ABC'������������
- ���������������������������������a���������������������������'ABC'
b = a
���������������������b������������a���������������������
��������������������������������������������������������������������
���������������������
���Python������������������������������������������������������
PI = 3.14159265359
������������PI
������������������������Python������������������������������PI
������������������
���������������������������������������������������������������������������������������������������������������PI
���������������������������������
���������
������������������������'
������������"
���������������������������
print("I'm OK")print('I\'m \"OK\"!')
I'm OKI'm "OK"!
������������������������������������������������������������������������\
���
���������������Python������������r''
������''
������������������������������������
print(r'\\\t\\')
\\\t\\
������������������������������������������\n
���������������������������������������������Python���������'''...'''
������������������������������
language = '''JavaPythonGolang'''print(language)
JavaPythonGolang
���������������'''...'''
������������������������r
���������
text = r'''I'm "OK"!I'm "OK"!'''print(text)
I'm "OK"!I'm "OK"!
UTF-8
���������������Unicode
������������������������������������������1-6������������
���������������������������������1���������������������������3������������������������������������������������������4-6������������
������������Python3���������������������������Unicode
���������������������������Python������������������������������
������������������������������Python���������ord()
������������������������������������chr()
������������������������������������������
ord('A')
65
chr(65)
'A'
ord('���')
20013
chr(20013)
'���'
���������������������������������������������������������������������str
'\u4e2d\u6587'
'������'
������Python���������������������str
������������������Unicode
���������������������������������������������
���������������������������������������������������������������������str
���������������������������bytes
���
Python���bytes
���������������������b
���������������������������������������
x = b'ABC'
���������������'ABC'
���b'ABC'
������������str
���������������������������������������������������bytes
������������������������������������������
���Unicode
���������str
������encode()
������������������������������bytes
���
'ABC'.encode('ascii')
b'ABC'
'������'.encode('utf-8')
b'\xe4\xb8\xad\xe6\x96\x87'
������������str
���������ASCII
���������bytes
���������������������������������������str
���������UTF-8
���������bytes
���
���������������str
���������ASCII
���������������������������������������������ASCII
������������������Python������������
���������������������������������������������������������������������������������������������bytes
;
������bytes
������str
���������������decode()
���������
b'ABC'.decode('ascii')
'ABC'
b'\xe4\xb8\xad\xe6\x96\x87'.decode('utf-8')
'������'
������bytes
���������������������������������decode()
������������������
������bytes
���������������������������������������������������errors='ignore'
������������������������
b'\xe4\xb8\xad\xff'.decode('utf-8', errors='ignore')
'���'
���������str
���������������������������������len()
���������
len('ABC')
3
len('���������')
3
len()
������������������str
���������������������������bytes
���len()
���������������������������
len(b'ABC')
3
len('���������'.encode('utf-8'))
9
���������1���������������������UTF-8
������������������������3���������������1������������������������1������������
������������������������������������������str
���bytes
���������������������������������������������������������������������UTF-8
���������str
���bytes
���������������
������Python������������������������������������������������������������������������������������������������������������������������������������������������UTF-8
���������
���Python���������������������������������������������UTF-8
������������������������������������������������������������
#!/usr/bin/env python3# -*- coding: utf-8 -*-
������������������������������Linux/OS X
���������������������Python������������������Windows
������������������������������
������������������������������Python������������������UTF-8
������������������������������������������������������������������������������������������
Python���������������������������������������������
name = '���������'age = 20score = 100str1 = f'���������{name} ���������{age} ���������{score:.2f}'str2 = '���������%s ���������%d ���������%.2f' % (name, age, score)str3 = '���������{0} ���������{1} ���������{2:.2f}'.format(name, age, score)print(str1)print(str2)print(str3)
������������������ ���������20 ���������100.00������������������ ���������20 ���������100.00������������������ ���������20 ���������100.00
������
������(list
)���Python������������������������������
list
������������������������������������������������������������������������
���������������������������������������������������������������list
���������
heros = ['���������', '���������', '���������', '������']heros
['���������', '���������', '���������', '������']
type(heros)
list
���len()
������������������list
������������������
len(heros)
4
������������������list
������������������������������������������������0
������������
heros[0]
'���������'
heros[1]
'���������'
���������������������������������������������������������������������������-1
���������������������������������������������
heros[-1]
'������'
������������������������������������2������
heros[-2]
'���������'
list
������������������������������������������������list
���������������������������
heros.append('������')heros
['���������', '���������', '���������', '������', '������']
������list
���������������������pop()
���������
heros.pop()
'������'
heros
['���������', '���������', '���������', '������']
���������������������������������������������������������������������������������������
heros[1] = '���������'heros
['���������', '���������', '���������', '������']
list
������������������������������������������������
������������list
���������������������������������������������list
������������������0���
L = []len(L)
0
������
���������������������������������tuple
tuple
���list
���������������������tuple
���������������������������������
������������������������������������()
������������������������������[]
���
heros = ('���������', '���������', '���������', '������')heros
('���������', '���������', '���������', '������')
type(heros)
tuple
len(heros)
4
���������append()
���insert()
������������������
������������������������������list
���������������������������������������heros[0]
���heros[-1]
���������������������������������������
heros[0]
'���������'
heros[-1]
'������'
������������tuple
������������������
������tuple
���������������������������������������������������������tuple
������list
������������tuple
���
tuple
������������������������������tuple
���������������������������������������
���������������������������tuple
���������������()
:
type(())
tuple
len(())
0
������������1������������tuple
���������������������,
heros = ('���������',)print(type(heros), heros[0])
���������
���������������������������������������
heros = ('���������')print(type(heros), heros[0])
���
������
Python���������������(dict
)������������dict
������dictionary
������������������������������map
������������-������key-value
������������������������������������������
���������������������������������������������������������������������������������������������dict
���������
d = {'���������': '������������', '���������': '������������', '������': '���������������'}d
{'���������': '������������', '���������': '������������', '������': '���������������'}
type(d)
dict
d['���������']
'������������'
���������������dict
���������������������������������������������������������key
���������
d['���������'] = '������������'d['���������']
'������������'
������������key
������������������value
���������������������������key
������value
������������������������������������������
d['���������'] = '���������������'d['���������']
'���������������'
������key
������������dict
���������������
���������key
���������������������������������������
- ������������in������key������������
- ������������
dict
���������get()
���������������key
������������������������None
������������������������value
'������' in d
False
print(d.get('������'))
None
d.get('������', '���������������')
'���������������'
���������������key
������pop(key)
������������������value
���������dict
������������
d.pop('���������')
'���������������'
d
{'���������': '������������', '���������': '������������', '������': '���������������'}
���������������:
dict
������������������������key
������������������������������������dict
���������������������������������������������dict
���key
���������������������������- ���Python������������������������������������������������������������������������������
key
������list
������������������������������key
���
������
set
���dict
���������������������key
������������������������value
���������key
���������������������������set
���������������������key
���
set1 = set([1, 2, 3, 2, 3])set2 = {2, 2, 3, 5, 5}print(type(set1), set1)print(type(set2), set2)
{1, 2, 3} {2, 3, 5}
���������������
set1.add(6)set1
{1, 2, 3, 6}
���������������
set1.remove(6)set1
{1, 2, 3}
set
���������������������������������������������������������������������������������set
������������������������������������������������������
set1 & set2
{2, 3}
set1 | set2
{1, 2, 3, 5}
set
���dict
���������������������������������������������value
���
set
������������dict
���������������������������������������������������������������������������������������������������������������������������set
���������������������������������
���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������
���������������������
������Python������������������������if
���������������True
������������������������print
���������������������������������������������
������������if
������������else
���������������������������if
���������False
���������������if
������������������else
������������
# ���������������������������:age = 16if age >= 18: print('your age is', age) print('adult')else: print('your age is', age) print('teenager')
your age is 16teenager
if
���������������������������������������������������������������������������������True
���������������������������������������������������������������elif
���else
���
age = 20if age >= 6: print('teenager')elif age >= 18: print('adult')else: print('kid')
teenager
if
������������������������������������x
������������������������������������������list
������������������True
������������False
���
x = [1, 2, 3]if x: print(x)
[1, 2, 3]
input()
������������������������str
���str
������������������������������������������str
������������������Python���������int()
������������������������������
s = input('birth: ')birth = int(s)if birth < 2000: print('00���')else: print('00���')
birth: 202100���
������������������������������������������������������������������������������������������
Python������������������������������for...in
������������������list
���tuple
���dict
���set
���������������������������������
names = ['���������', '���������', '������']for name in names: print(name)
������������������������
d = {'���������': '������������', '���������': '������������', '������': '���������������'}for k, v in d.items(): print(k, ':', v)
��������� : ��������������������� : ������������������ : ���������������
for x in ...
���������������������������������������x
������������������������������������
������������������������1-10
���������������������������������sum
������������������
sum = 0for x in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: sum += xprint(sum)
55
���������������1-100
���������������������1������100���������������
������Python������������range()
���������������������������������������������������list()
���������������������list
���
������range(5)
���������������������0������������5������������
list(range(5))
[0, 1, 2, 3, 4]
sum = 0for x in range(101): sum = sum + xprint(sum)
5050
������������������while
���������������������������������������������������������������������������������
���������������������100���������������������������������������while
���������������
sum = 0n = 99while n > 0: sum += n n -= 2print(sum)
2500
������������������������������
break
���������������������������������������������continue
���������������������������������������������������������������
������
������������
Python���������������������������������������������������������������������������������������������help(abs)
������abs
������������������������
help(abs)
Help on built-in function abs in module builtins:abs(x, /) Return the absolute value of the argument.
������abs
���������
abs(-3.14)
3.14
abs(100)
100
max
������������������������������, ������������������������
max(1, 10)
10
max(1, 100, 50)
100
Python���������������������������������������������������������������int()
���������������������������������������������������
int('123') + 7
130
int(12.34)
12
float('2.14') + 1
3.14
type(str(1.23))
str
bool(1)
True
bool(0)
False
bool('')
False
���������������������������������������������������������
������������������������������������������������������������������������������������������������
# ������a������abs������a = abs# ���������������������a������abs������a(-1)
1
������������
���Python���������������������������������def
���������������������������������������������������������������������:
������������������������������������������������������������������return
���������������
���������������������������������my_abs
���������������
def my_abs(x): return x if x >= 0 else -xmy_abs(-100)
100
������������return
������������������������������������������������������������������None
���
return None
���������������return
���
���������������������������������������������������������������pass
���������
def nop(): pass
pass
������������������������������������������
���������pass
������������������������������������������������������������������������������������������������������pass
������������������������������
pass
������������������������������, ���������������pass
���������������������������������������
if age >= 18: pass
Python���������������������������������
def swap(x, y): return y, xnum1, num2 = 1, 2print(num1, num2)num1, num2 = swap(num1, num2)print(num1, num2)
1 22 1
������������������������������Python������������������������������������
t = swap(10, 20)print(type(t), t)
(20, 10)
������������������������tuple
���
������������������������������������tuple
������������������������������������������������������������tuple
���������������������������������
���������Python���������������������������������������������tuple
���������������������������
���������������
������������������������������������������������������������������������������������������������������
Python���������������������������������������������������������
������������������������������������������������������������������������������������������������������
���������������������������������������������������������������������������������������������������������
������������������x
���������������������
def power(x): return x * xpower(10)
100
���������������x
���3������������������
���������������������power3
������������������������������x
���4���������5������������������������
���������power(x)
���������power(x, n)
���������������x
���n
���������
def power(x, n): s = 1 while n > 0: n -= 1 s *= x return s
������������������������������������������������������������������������x
���n
���
power(2, 10)
1024
������power(x, n)
���������������������������������������������������������������������������������������������������������������������������������������������������������������������
������������������������������������������������������������������������x
���������������������������������������������������n
���������������������2
:
def power(x, n=2): s = 1 while n > 0: n -= 1 s *= x return s
power(10)
100
power(2, 10)
1024
���������������������������������������������������������������������������������������
���������������������: ������������������������������������������������n=2
������������������������������������������������������������������������������������������������
������������������������������������������������������������������������
������������������������������������������:
- ������������������������������������������
- ���������������������������������������������������������������������������������������������������������������
- ������������������������������������������������������������������������
������������������������������
def add_end(L=[]): L.append('END') return L
add_end()
['END']
add_end()
['END', 'END']
add_end()
['END', 'END', 'END']
���������������������������������������������
���������Python���������������������������������������L
���������������������������������[]
���������������������L
������������������������������������[]
���
���������������������������������������L
���������������������������������������������������������������������������������������������[]
������
������������������������������������None
������������������������������
def add_end(L=None): if L is None: L = [] L.append('END') return L
add_end()
['END']
add_end()
['END']
���������������������������������������str
���None
���������������������������
������������������������������������������������������������������������������������������������������������������������������
���������������������������������������������������������������������������������������������������������������������
������������������������������������������������������������������������������������������������
���Python������������������������������������������
������������������������������������������������������������������������������1������2������������������������������0������
������������������������������������������a���b���c...
������������a*a + b*b + c*c + ...
���������������������������������������������������������������������������������������������������������������������������������������tuple
������������
def calc(nums): sum = 0 for n in nums: sum = sum + n * n return sum
������������������������������������������tuple
���
nums = (1, 2, 3)calc(nums)
14
��������������������������������� ���������������������������������������������������������������������
������������������������������������������������������������������������*
������
def calc(*nums): sum = 0 for n in nums: sum = sum + n * n if len(nums) == 3: print(type(nums)) return sum
���������������������������������������������������������0������������
calc()
0
# ������1���������calc(1)
1
# ������2���������calc(1, 2)
5
# ������3���������calc(1, 2, 3)
14
���������������������������������������nums
���������������������tuple
���
���������������������list
������tuple
������������������������������������������
Python���������list
���tuple
���������������*
���������list
���tuple
���������������������������������������
nums = [1, 2, 3, 4]calc(*nums)
30
���������������������������0���������������������������������������������������������������������������������tuple
���
������������������������������0������������������������������������������������������������������������������������������������dict
���
def person(name, age, **kw): print('name:', name, 'age:', age, type(kw), kw)
person('���������', 20)
name: ��������� age: 20{}
person('���������', 20, skill='������������', wife='���������')
name: ��������� age: 20{'skill': '������������', 'wife': '���������'}
���������������������������������������������������������������
������������person
������������������������������������������������������������������������������������������������������������������������������������������������������
���������������������������������������������������dict
������������������dict
������������������������������������
d = {'skill': '������������', 'wife': '���������'}person('���������', 20, **d)
name: ��������� age: 20{'skill': '������������', 'wife': '���������'}
**d
���������d
������dict
���������key-value
������������������������������������**kw
���������kw
���������������dict
���
���������kw
���������dict
���d
���������������������kw
������������������������������������d
���
������������������������
def person(name, age, **kw): kw['job'] = '������������' print('name:', name, 'age:', age, id(kw), kw)d = {'skill': '������������', 'wife': '���������'}print('���������:', id(d), d)person('���������', 20, **d)print('���������:', id(d), d)
���������: 4594582016 {'skill': '������������', 'wife': '���������'}name: ��������� age: 20 4594584192 {'skill': '������������', 'wife': '���������', 'job': '������������'}���������: 4594582016 {'skill': '������������', 'wife': '���������'}
������������������������������������������������������������������������������������������
def calc(*nums): print('���������', type(nums), id(nums), nums) sum = 0 for n in nums: sum = sum + n * n return sumnums = (1, 2, 3)print('���������:', id(nums), nums)calc(*nums)print('���������:', id(nums), nums)
���������: 4594465408 (1, 2, 3)���������4594472896 (1, 2, 3)���������: 4594465408 (1, 2, 3)
������������������������������������������������������������������������������
������������������**kw
���������������������������������������������������������*
���*
������������������������������������������������
������������������skill
���wife
������������������������
def person(name, age, *, skill, wife): print(name, age, skill, wife)person('������', 18, skill='���������������', wife='������')
������ 18 ��������������� ������
������������������������������������������������������������������������������������������������������������������������������*
������
def person(name, age, *args, skill, wife): print(name, age, args, skill, wife) person('������', 18, '���������������', skill='���������������', wife='������')
������ 18 ('���������������',) ��������������� ������
���������������������������������������������������������������������������������������������
���������������������������������������������������������������
def person(name, age, *, skill='������', wife='������'): print(name, age, skill, wife)person('������', 21)person('������', 21, skill='������������')person('������', 21, wife='���������')
������ 21 ������ ������������ 21 ������������ ������������ 21 ������ ���������
������������������������������������������������������������������������������������������������*
������������������������������������*
���Python���������������������������������������������������������������
���Python���������������������������������������������������������������������������������������������������������������������5���������������������������������
���������������������������������������������������������������������������������������������������������������������������������
def f1(a, b, c=0, *args, **kw): print('a =', a, 'b =', b, 'c =', c, 'args =', args, 'kw =', kw)def f2(a, b, c=0, *, d, **kw): print('a =', a, 'b =', b, 'c =', c, 'd =', d, 'kw =', kw) f1(1, 2)f1(a=1, b=2)f1(1, 2, c=3)f1(1, 2, 3, 'a', 'b')f1(1, 2, 3, 'a', 'b', x=99)f2(1, 2, d=99, ext=None)
a = 1 b = 2 c = 0 args = () kw = {}a = 1 b = 2 c = 0 args = () kw = {}a = 1 b = 2 c = 3 args = () kw = {}a = 1 b = 2 c = 3 args = ('a', 'b') kw = {}a = 1 b = 2 c = 3 args = ('a', 'b') kw = {'x': 99}a = 1 b = 2 c = 0 d = 99 kw = {'ext': None}
���������������������������tuple
���dict
������������������������������������
args = (1, 2, 3, 4)kw = {'d': 99, 'x': '#'}f1(*args, **kw)
a = 1 b = 2 c = 3 args = (4,) kw = {'d': 99, 'x': '#'}
args = (1, 2, 3)kw = {'d': 88, 'x': '#'}f2(*args, **kw)
a = 1 b = 2 c = 3 d = 88 kw = {'x': '#'}
���������������������������������������������������func(*args, **kw)
������������������������������������������������������������
������������������������5���������������������������������������������������������������������������������������������
���������
- ������������������������������������������������������������������������������������������������������
*args
������������������args
������������������tuple
**kw
���������������������kw
������������������dict
- ������������������������������������
func(1, 2, 3)
���������������������list
���tuple
������������*args
���������func(*(1, 2, 3))
- ���������������������������������������
func(a=1, b=2)
���������������������dict
������������**kw
���������func(**{'a': 1, 'b': 2})
- ������
*args
���**kw
���Python��������������������������������������������������������������������������������� - ������������������������������������������������������������������������������������������������������
- ���������������������������������������������������������������������������������������
*
������������������������������������
������������
������������������������������������������������������������������������������������������������������������������������������
fact(n)
���������������n x fact(n-1)
���������n=1
������������������������
def fact(n): if n==1: return 1 return n * fact(n - 1)
fact(1)
1
fact(3)
6
fact(5)
120
������������
���Python������������������������������������������������������������������������������������������������������������
���������������������������������Python���������������������������������1���������������������������������������5������������������������������������������������������������������
������
���������������������������������������������������������������������������Python������������������Slice
���������������������������������������������
L = ['���������', '���������', '���������', '������']
# ������3���������L[0:3]
['���������', '���������', '���������']
L[0:3]
������������������0������������������������3���������������������������3������������0���1���2������������3������������
# ������������������������0������������������L[:3]
['���������', '���������', '���������']
# ���������1���������������2���������������L[1:3]
['���������', '���������']
Python������L[-1]���������������������������������������������������������
L[-2:]
['���������', '������']
���������������������������������������-1���
���������������������
# ���������������0-19���������L = list(range(20))L
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
# ������10������L[:10]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
# ������10������L[-10:]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
# ���11-20������L[10:20]
[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
# ���10���������������������������L[:10:2]
[0, 2, 4, 6, 8]
# ���������������5������������L[::5]
[0, 5, 10, 15]
# ������������������������[:]���������������������������listL[:]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
tuple
������������list
������������������tuple
���������������������tuple
������������������������������������������������������tuple
(0, 1, 2, 3, 4, 5)[:3]
(0, 1, 2)
���������'xxx'������������������������list
���������������������������������������������������������������������������������������������������������������������
'iflyendless'[:4]
'ifly'
'iflyendless'[::3]
'iyds'
���������������������������������������������������������������������������������������substring
���������������������������������������������Python���������������������������������������������������������������������������������������������������
������
������������list
���tuple
���������������������for
���������������������list
���tuple
������������������������������������Iteration
������
Python���for
������������������������list
���tuple
���������������������������������������������������
list
���������������������������������������������������������������������������������������������������������������������������������������������������������������
# ������������for x, y in [(1, 1), (2, 4), (3, 9)]: print(x, y)
1 12 43 9
# ������������for e in ('���������', 30, '������������'): print(e)
���������30������������
# ������������for name in {'���������', '���������', '���������', '������'}: print(name)
���������������������������������
������������������������������
d = {'���������': '������������', '���������': '������������', '������': '���������������'}
# ���������������keyfor key in d: print(key)
������������������������
������������������dict
������������key
���
# ���������������valuefor value in d.values(): print(value)
���������������������������������������
# ������������key���valuefor k, v in d.items(): print(k, v)
��������� ��������������������� ������������������ ���������������
������������������������������������������������������������for
���������
for ch in '������������������': print(ch)
������������������
������������������for
���������������������������������������������������for
������������������������������������������������������������������list
���������������������������
������������������������������������������������������������������������collections
���������Iterable
���������������
from collections.abc import Iterableisinstance('https://www.cnblogs.com/iflyendless/', Iterable)
True
isinstance([1,2,3], Iterable)
True
isinstance(123, Iterable)
False
������������list
������������Java���������������������������������Python���������enumerate
���������������������list
������������-
������������������������������for
���������������������������������������������
for i, value in enumerate(['���������', '���������', '���������']): print(i, value)
0 ���������1 ���������2 ���������
���������������
������������������List Comprehensions
������Python���������������������������������������������������list
���������������
������������������������list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
���������list(range(1, 11))
���
list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
������������������[1x1, 2x2, 3x3, ..., 10x10]
������������������������������������������������������������
[x * x for x in range(1, 11)]
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
���������������������������������������������x * x
������������������������for
���������������������list
���������������������������������������������������������������������������������
for
���������������������������if
������������������������������������������������������
[x * x for x in range(1, 11) if x % 2 == 0]
[4, 16, 36, 64, 100]
������������������������������������������������������
[x + y for x in 'ABC' for y in '12']
['A1', 'A2', 'B1', 'B2', 'C1', 'C2']
������������������������������������������������������������������������������������
���������������������������������������������������list
:
d = {'���������': '������������', '���������': '������������', '������': '���������������'}[k + '=' + v for k, v in d.items()]
['���������=������������', '���������=������������', '������=���������������']
���������list
������������������������������������
L = ['JAVA', 'SCALA', 'PYTHON', 'GOLANG'][x.lower() for x in L]
['java', 'scala', 'python', 'golang']
[x if x % 2 == 0 else -x for x in range(1, 11)]
[-1, 2, -3, 4, -5, 6, -7, 8, -9, 10]
������������������������������for
���������if ... else
������������������for
���������if
���������������������������else
���
���������
���������������������������������������������������������������������������������������������������������������������������������������������������100������������������������������������������������������������������������������������������������������������������������������������������������������������������������������
������������������������������������������������������������������������������������������������������������������������������������������������������������������������list
������������������������������������Python������������������������������������������������������������������generator
���
���������������generator
������������������������������������������������������������������������������������[]
������()
���������������������generator
���
g = (x * x for x in range(10))g
at 0x11364ee40>
������������������������������������������������next()
������������generator
������������������������
next(g)
0
next(g)
1
next(g)
4
generator
���������������������������������next(g)
���������������g
������������������������������������������������������������������������������������������������StopIteration
������������
������������for
���������������generator
������������������������
g = (x * x for x in range(5))for n in g: print(n)
014916
generator
������������������������������������������������������������������������������for
������������������������������������������������������������
���������������������������������������Fibonacci
������������������������������������������������������������������������������������������1, 1, 2, 3, 5, 8, 13, 21, 34, ...
������������������������������������������������������������������������������������������������������
def fib(max): n, a, b = 0, 0, 1 while n < max: print(b) a, b = b, a + b n = n + 1 return 'done'
fib(5)
11235
'done'
������������������������������fib
���������������������������������������������������������������������������������������������������������������������������������������������������������������generator
���
���������������������������������generator
������������������������fib
������������generator
���������������print(b)
������yield b
���������������
def fib(max): n, a, b = 0, 0, 1 while n < max: yield b a, b = b, a + b n = n + 1 return 'done'
���������������generator
������������������������������������������������������yield
���������������������������������������������������������������������������generator
���
f = fib(6)f
������������������������������generator
������������������������������������������������������������������return
���������������������������������������������������������generator
���������������������������next()
������������������������yield
������������������������������������������������yield
������������������������
next(f)
1
next(f)
1
next(f)
2
next(f)
3
next(f)
5
���������
���������������������for
���������������������������������������
- ������������������������
list
���tuple
���dict
���set
���str
��� generator
������������������������yield
���generator function
���������������������������for
������������������������������������������Iterable
���
������������isinstance()
���������������������������Iterable
���������
from collections.abc import Iterableisinstance([], Iterable)
True
isinstance({}, Iterable)
True
isinstance('abc', Iterable)
True
isinstance((x for x in range(10)), Iterable)
True
isinstance(100, Iterable)
False
���������������������������������for
���������������������next()
������������������������������������������������������������StopIteration
������������������������������������������������
���������next()
������������������������������������������������������������������Iterator
���
������������isinstance()
���������������������������Iterator
���������
from collections.abc import Iteratorisinstance((x for x in range(10)), Iterator)
True
isinstance([], Iterator)
False
isinstance({}, Iterator)
False
isinstance('abc', Iterator)
False
���������������Iterator
������������list
���dict
���str
���������Iterable
������������Iterator
���
���list
���dict
���str
���Iterable
������Iterator
������������iter()
���������
isinstance(iter([]), Iterator)
True
isinstance(iter('abc'), Iterator)
True
���������list
���dict
���str
���������������������Iterator
���
������������Python���Iterator
������������������������������������Iterator
���������������next()
������������������������������������������������������������������������StopIteration
���������������������������������������������������������������������������������������������������������������������������������next()
������������������������������������������������Iterator
���������������������������������������������������������������������������������
Iterator
���������������������������������������������������������������������������������list
���������������������������������������������
���������
- ������������������
for
���������������������Iterable
��������� - ������������������
next()
���������������������Iterator
��������������������������������������������������� - ���������������������
list
���dict
���str
������Iterable
���������Iterator
���������������������iter()
������������������Iterator
���������
Python���for
���������������������������������������next()
������������������
for x in [1, 2, 3, 4, 5]: pass
���������������������������
# ������������Iterator������:it = iter([1, 2, 3, 4, 5])# ������:while True: try: # ������������������: x = next(it) except StopIteration: # ������StopIteration��������������� break
���������������
������������������������������������������������������������Functional Programming
���������������������������������������������������������������������������������������������
������������������������������������������������������������������������������������������������������������������������������
������������
������������������������, ���������������������������������������
f = absf
f(-10)
10
���������������������, ���������������������������������������������������abs()
���������������������������������������abs
���������������������������������������������������������������
def my_abs(x): return x if x >= 0 else -xprint(my_abs(-10))print(my_abs(10))# ���my_abs������������������my_abs = 100try: my_abs(-10)except BaseException as e: print(e)
1010'int' object is not callable
���my_abs
������100���������������������my_abs(-10)
���������������������������my_abs
���������������������������������������������������������������������10���
���������������������������������������������������������������������������������������
���������������������abs
���������������������������import builtins
���������������������������������abs
������������������������������������������������import builtins; builtins.abs = 10
���
������������������������������������������������������������������������������������������������������������������������������������������������������������������������
# ������������������������������def add(x, y, f): return f(x) + f(y)
def f1(x): return x * xadd(2, 3, f1)
13
map
map()
������������������������������������������������������Iterable
���map
���������������������������������������������������������������������������������Iterator
���������
r = map(f1, [1, 2, 3, 4, 5])list(r)
[1, 4, 9, 16, 25]
map()
���������������������������f1
���������������������������������������r���������Iterator
���Iterator
������������������������������list()
���������������������������������������������������������list���
���������map()
������������������������������������������������������������������������������������������������������f(x)=x*x
������������������������������������������������������������list���������������������������
list(map(str, [1,2,3]))
['1', '2', '3']
reduce
reduce
������������������������������������[x1, x2, x3, ...]
���������������������������������������������reduce
������������������������������������������������������������������������������reduce(f, [x1, x2, x3, x4]) = f(f(f(x1, x2), x3), x4)
���������������������������������������������reduce
������,������������������������������Python������������sum()
def add(x, y): return x + yfrom functools import reducereduce(add, [1, 2, 3, 4, 5])
15
# ������������������lambda������������������������reduce(lambda x, y: x + y, [1, 2, 3, 4, 5])
15
filter
filter()
���������������������������
���map()
���������filter()
������������������������������������������map()
���������������filter()
������������������������������������������������������������������������True
������False
������������������������������������
# ���������list���,���������������������������������list(filter(lambda x: x % 2 == 1, [1, 2, 3, 4, 5]))
[1, 3, 5]
# ���������������������������������������������������������list(filter(lambda x: x and x.strip(), ['ab','','c',' ','d', None]))
['ab', 'c', 'd']
���������filter()
������������������������������������������������������������������������
���������filter()
������������������������Iterator
������������������������������������������������filter()
������������������������������list()
���������������������������������list���
sorted
���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������dict
������������������������������������������������������������������������������������������������������������������
# Python���������sorted()������������������list������������sorted([36, 5, -12, 9, -21])
[-21, -12, 5, 9, 36]
���������sorted()
���������������������������������������������������������key
���������������������������������������������������������������������
sorted([36, 5, -12, 9, -21], key=lambda x: x if x >= 0 else -x)
[5, 9, -12, -21, 36]
������������������������������������key
������������������������������������reverse=True
sorted([36, 5, -12, 9, -21], key=lambda x: x if x >= 0 else -x, reverse=True)
[36, -21, -12, 9, 5]
���������������������������������������������������������������������������������������������������������������������������������
������������
������������������������������������������������������������������������������������������������
# ������������������������������y=a*x+b������def f(a, b): def y(x): return a * x + b; return y# y = 2*x + 1y = f(2, 1)y(10)
21
���������������f(a, b)
���������������������y������������������������y���������������������������������a, b������f(a, b)
������������y���������������������������������������������������������������������������������Closure���
���������������������������������������
������������������������������������f(a, b)
���������������������������������������������������������������������������������
y1 = f(2, 1)y2 = f(2, 1)y1 == y2
False
���������������������������������������������������������������������������������������������������������������������������������
def count(): fs = [] for i in range(1, 4): def f(): return i*i fs.append(f) return fsf1, f2, f3 = count()
���������������������f1()
���f2()
���f3()
���������������1���4���9������������������������
f1()
9
f2()
9
f3()
9
������������9������������������������������������������������i������������������������������������3������������������������������������������������i���������������3������������������������9���
������������������������������������������������������������������������������������������������������������������
������������
���������������������������������������������������������������������������������������������������������������������������������
list(map(lambda x: x * x, [1, 2, 3, 4, 5]))
[1, 4, 9, 16, 25]
���������lambda
���������������������:
���������x
���������������������
���������������������������������������������������������������������return
������������������������������������������
���������������������������������������������������������������������������������������
������������������������������������������������������������������������������������������������������������������������������������
f = lambda x: x * xf
(x)>
f(6)
36
������������������������������������������������������������������
def f(a, b): return lambda x: a * x + b
y = f(2, 1)y
. (x)>
y(3)
7
���������
���������������������__name__
���������������������������������������
def hello(): print("My blog is https://www.cnblogs.com/iflyendless/.") hello.__name__
'hello'
���������������hello()
������������������������������������������������������������������������������������������hello()
������������������������������������������������������������������������������������������������������Decorator
������
������������decorator
������������������������������������������������������������������������������������������decorator
������������������������
def log(func): def wrapper(*args, **kw): print(f'***Before {func.__name__}������***') r = func(*args, **kw) print(f'***After {func.__name__}������***') return r return wrapper
���������������log
���������������������decorator
���������������������������������������������������������������������������������Python���@
������������decorator
���������������������������
@logdef hello(): print("My blog is https://www.cnblogs.com/iflyendless/.")
hello()
***Before hello������***My blog is https://www.cnblogs.com/iflyendless/.***After hello������***
���������
���������������������������������������������������������������������������������������������������������������������������������������������������������
int()
���������������������������������������������������������������������int()
������������������������������
int('11')
11
���int()
������������������������base
���������������������10���������������base
���������������������N������������������
int('11', base = 2)
3
������������������������������������������������������������int(x, base=2)
������������������������������������������int2()
���������������������base=2
���������������������
def int2(x, base=2): return int(x, base)# ���������������������������������������int2('11')
3
functools.partial
������������������������������������������������������������������������int2()
������������������������������������������������������������int2
���
import functoolsint2 = functools.partial(int, base=2)int2('11')
3
���������������������functools.partial
������������������������������������������������������������������������������������������������������������������������������������������������������������
������������������������int2
���������������������base
������������������������������2���������������������������������������������������
int2('11', base = 10)
11
������������������������������������������������������
���*args
���**kw
���3������������������������
int2 = functools.partial(int, base=2)
������������������int()
������������������������base���������������int2('11')
������������
kw = { 'base': 2 }int('11', **kw)
3
������������������
my_max = functools.partial(max, 10)my_max(1, 3, 5)
10
���������������10
������*args
���������������������������������������������my_max(1, 3, 5)
������������
args = (10, 1, 3, 5)max(*args)
10
������������������������������������������������������������������functools.partial
������������������������������������������������������������������������������������������������������������������������
������
���������������������������������������������������������������������������������������������������������������������������
������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Python������������.py
���������������������������������Module
������
������������������������������
- ���������������������������������������
- ���������������������������������������������������������������������������������������������������������������������������������������������������������������������Python���������������������������������������������
- ���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������
������Python������������������������
������������������������������������������������������������������������������������Python������������������������������������������������������������Package
������
���������������������abc.py
������������������������������abc
������������������xyz.py
������������������������������xyz
������������
������������������������abc
���xyz
������������������������������������������������������������������������������������������������������������������������������������������������������mycompany
������������������������������
mycompany������ __init__.py������ abc.py������ xyz.py
������������������������������������������������������������������������������������������������������������������abc.py
���������������������������mycompany.abc
���������������xyz.py
���������������������mycompany.xyz
���
���������������������������������������������������__init__.py
������������������������������������������������������Python������������������������������������������������������������
__init__.py
���������������������������������Python���������������__init__.py
���������������������������������������������������mycompany
��� ���������������������������������������������������������������������������������������������������
mycompany ������ web ��� ������ __init__.py ��� ������ utils.py ��� ������ www.py ������ __init__.py ������ abc.py ������ utils.py
������www.py
������������������mycompany.web.www
���������������utils.py
���������������������mycompany.utils
���mycompany.web.utils
���
���������������������������������������������������������Python������������������������������������������������������sys
������������������������������������������sys.py
���������������������������������������sys
���������
������������������������Python������������������������������������������������������������������������������
���������������������������������������
- ������������������Python���������������������������������������������������������
- ������������������������������������������������������������������������������������������������������������Python������������������
import abc
���������������������������������������������
������������
Python���������������������������������������������������������������������������������������������������������
������������sys
���������������������������hello
���������
#!/usr/bin/env python3# -*- coding: utf-8 -*-' a test module '__author__ = 'Michael Liao'import sysdef test(): args = sys.argv if len(args)==1: print('Hello, world!') elif len(args)==2: print('Hello, %s!' % args[1]) else: print('Too many arguments!')if __name__=='__main__': test()
- ���1���������2������������������������1������������������������
hello.py
���������������Unix/Linux/Mac
���������������2���������������.py
������������������������UTF-8
��������� - ���4���������������������������������������������������������������������������������������������������������������������������������
- ���6���������
__author__
���������������������������������������������������������������������������������������������
������������Python���������������������������������������������������������������������������������������������������������
������������������������������������������
������sys
���������������������������������������������import sys
������sys
���������������������������������sys
������������������������sys
������������������������������sys
������������������������
sys
���������������argv
������������list
������������������������������������argv
���������������������������������������������������������.py
���������������������������
- ������
python3 hello.py
���������sys.argv
������['hello.py']
��� - ������
python3 hello.py iflyendless
���������sys.argv
������['hello.py', 'iflyendless']
���
������������������������������������
if __name__=='__main__': test()
���������������������������hello
������������������Python������������������������������__name__
������__main__
������������������������������������hello
������������if���������������������������������if������������������������������������������������������������������������������������������������������������������
������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Python���������������_
���������������������
������������������������������������������public
���������������������������������������abc
���x123
���PI
������
������__xxx__
������������������������������������������������������������������������������������������������__author__
���__name__
���������������������hello
���������������������������������������������������__doc__
���������������������������������������������������������������
������_xxx
���__xxx
���������������������������������������������private
���������������������������������������_abc
���__abc
������
���������������������private
������������������������
������������������������������������������������������������������Python���������������������������������������������private
������������������������������������������������������������private
������������������
������������������������������private
���������������������
���������������private
������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������
������������������������������������������������������private
������������������������������������������������public
���
���������������������
���������������������������������������������������pip
���������
���������Python������������������������������������������������������������MySQL���������������Web������Flask���������������Numpy���������pip������������������������������������������������������������������������������������Anaconda
���������������������Python���������������������������������������������������������������������������������������������������������Anaconda
���������������������������������������������������������������������������������������
������������������������Anaconda
������������Path
������python���������������������Python������������Anaconda
������������������������������������Anaconda
������������������������������������������������Python���������
���������������������������������������Python���������������������������������������.py
������������������������������������������ImportError: No module named xxx
������������������Python���������������������������������������������������������������������������������������������������������sys
���������path
������������
import syssys.path
['/Users/wind/notebook', '/Volumes/300g/opt/anaconda3/envs/test/lib/python38.zip', '/Volumes/300g/opt/anaconda3/envs/test/lib/python3.8', '/Volumes/300g/opt/anaconda3/envs/test/lib/python3.8/lib-dynload', '', '/Volumes/300g/opt/anaconda3/envs/test/lib/python3.8/site-packages', '/Volumes/300g/opt/anaconda3/envs/test/lib/python3.8/site-packages/aeosa', '/Volumes/300g/opt/anaconda3/envs/test/lib/python3.8/site-packages/IPython/extensions', '/Users/wind/.ipython']
���������������������������������������������������������������
- ������������
sys.path
������������������������������sys.path.append('...path/to/py_scripts...')
������������������������������������������������������������; - ������������������
PYTHONPATH
���������������������������������������������������������������������������������������������Path
���������������������������������������������������������������������Python������������������������������������������
������������
������������������������������������try...except...finally...
������������������������Python���������������
try
������������������
try: print('try...') r = 10 / 0 print('result:', r)except ZeroDivisionError as e: print('except:', e)finally: print('finally...')print('END')
try...except: division by zerofinally...END
������������������������������������������������������������try
������������������������������������������������������������������������������������������������������������������������������except
���������������������except
���������������finally
���������������������finally
������������������������������������
���������������������������������������������������������������������������������except
���������������������������������except���������������������������������
def f1(s): try: print('try...') r = 10 / int(s) print('result:', r) except ValueError as e: print('ValueError:', e) except ZeroDivisionError as e: print('ZeroDivisionError:', e) finally: print('finally...') print('END')
������������������������������
f1('2')
try...result: 5.0finally...END
������s
������int
������������������������
f1('a')
try...ValueError: invalid literal for int() with base 10: 'a'finally...END
���������0������������������
f1('0')
try...ZeroDivisionError: division by zerofinally...END
���������Python������������������������BaseException
���������������������������������������������������������������
���������������������Java������������������������������main()
������bar()
���bar()
������foo()
���������foo()
���������������������������main()
���������������������������������
���������
������������������������������������������������������������������Python������������������������������������������������������������������
������������������������������������������������������������������������������������������������������������������������������������������������������������������������
���������������������������������������������������������������������������������������������������
Python���������logging
������������������������������������������������
import loggingdef foo(s): return 10 / int(s)def bar(s): return foo(s) * 2def f(): try: bar('0') except Exception as e: logging.exception(e)f()print('END')
ERROR:root:division by zeroTraceback (most recent call last): File "", line 11, in f bar('0') File " ", line 7, in bar return foo(s) * 2 File " ", line 4, in foo return 10 / int(s)ZeroDivisionError: division by zero
END
������������������������������������������������������������������������������class
���������������������������������������raise
������������������������������������
class FooError(ValueError): passdef foo(s): n = int(s) if n==0: raise FooError('invalid value: %s' % s) return 10 / ntry: foo('0')except FooError as e: logging.exception(e)
ERROR:root:invalid value: 0Traceback (most recent call last): File "", line 11, in foo('0') File " ", line 7, in foo raise FooError('invalid value: %s' % s)FooError: invalid value: 0
���������������������������������������������������������������������������������Python���������������������������������������ValueError
���TypeError
������������������Python������������������������
���������������������������������������������������������������������������������������������������������������������������
def foo(s): n = int(s) if n==0: raise ValueError('invalid value: %s' % s) return 10 / ndef bar(): try: foo('0') except ValueError as e: print('ValueError!') raise
������������
������������������������Object Oriented Programming
���������OOP
������������������������������������������������������������������������������������������
OOP
������������������������������������������������������������������
������������������������
���
���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������
���Python���������������������������������������������������������������������������������������������������������������������������������������������Class
���������������
������������������������������������������������������������������������������������
class Hero(object): def __init__(self, name, skill): self.name = name self.skill = skill def say_hi(self): print(f'������������������{self.name}���������{self.skill}')
hero1 = Hero('���������', '������������')hero1.say_hi()
������������������������������������������������
hero2 = Hero('���������', '������������')hero2.say_hi()
������������������������������������������������
������������������������������������������������������������������������������������������
def say_hi(name, skill): print(f'������������������{name}���������{skill}')
say_hi('���������', '������������')say_hi('���������', '������������')
������������������������������������������������������������������������������������������������
������������������������������������������������������������������������������������������������������������������������������Hero
������������������������������������Hero
���������������������������������������������������������������������������������������������������������������������������������������name
���skill
���������������������������������������������������������list
������������������������������������������������������������2������������������Hero
������������������������������������������������������������Hero
���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Hero
������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������
������������������������������������������������������������������������������������������������������������������Class
���������������Instance
������������������������������Class
���������������������������������������������Class������Hero
������������������������������������������������Instance
������������������������������������������������������������
������������
������������������Hero
���
������Class
���������������������������������������������������������������������������������������������������������������������������������������������������������������
������������
������������������������������������������Class
���������������Instance
������������������������������������������������Hero
���������������������������������������������������������������������������������������������������������������������������������������������������
���Python������������������������class
������������
class Hero(object): passHero
__main__.Hero
class
������������������������������Hero
������������������������������������������������������(object
)���������������������������������������������������������������������������������������������������������������������������������object
������������������������������������������������
������������Hero
���������������������Hero
������������������������������������������������+()
������������
hero1 = Hero()hero1
<__main__.Hero at 0x1136dd490>
���������������������������������������������������������������������hero1
������������name
���������
hero1.name = '���������'hero1.name
'���������'
���������������������������������������������������������������������������������������������������������������������������������������������������������������������������__init__
������������������������������������������name
���skill
���������������������
class Hero(object): def __init__(self, name, skill): self.name = name self.skill = skill
���������������������__init__
���������������������������������������
__init__
���������������������������������self
���������������������������������������������__init__
������������������������������������������������self
���������self
���������������������������������
������__init__
������������������������������������������������������������������������������������__init__
���������������������������self
���������������Python���������������������������������������������
hero1 = Hero('���������', '���������������')
hero1.name
'���������'
hero1.skill
'���������������'
������������������������������������������������������������������������������������������������������������������self
������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������
������Hero
���������������������name
���skill
���������������������������������������������������������������������������������������������������Hero
���������������������������������������������������������������������������������������������������������������������������Hero
���������������������������������������������������������
���
class Hero(object): def __init__(self, name, skill): self.name = name self.skill = skill def say_hi(self): print(f'������������������{self.name}���������{self.skill}')
������������������������������������������������self
������������������������������������������������������������������������������������������������������������self
������������������������������������������
hero1 = Hero('���������', '���������������')hero1.say_hi()
���������������������������������������������������
���������������������������Hero
���������������������������������������������������name
���skill
������������������������������������Hero
������������������������������������������������������
������������������������������������������������������������������������
���������
- ���������������������������������������������������������������������������������������������������������������������������������������
- ���������������������������������������������������������������������������������������������������������
������������������������Python������������������������������������������������������������������������������������������������������������������������������������������������������������������������������
hero1 = Hero('���������', '������������')hero2 = Hero('���������', '������������')
hero2.wife = '���������'hero2.wife
'���������'
import loggingtry: hero1.wifeexcept AttributeError as e: logging.exception(e)
ERROR:root:'Hero' object has no attribute 'wife'Traceback (most recent call last): File "", line 3, in hero1.wifeAttributeError: 'Hero' object has no attribute 'wife'
������������
���Class���������������������������������������������������������������������������������������������������������������������������������������������������������������
������������������������������������������������������������
hero1 = Hero('���������', '���������������')hero1.skill
'���������������'
hero1.skill = '������������'hero1.skill
'������������'
���������������������������������������������������������������������������������������������__
������Python���������������������������������__
������������������������������������������private
������������������������������������������������������������������������Hero
���������������
class Hero(object): def __init__(self, name, skill): self.__name = name self.__skill = skill def say_hi(self): print(f'������������������{self.__name}���������{self.__skill}')
������������������������������������������������������������������������������������������������������.__skill
������
import logginghero1 = Hero('���������', '���������������')try: hero1.__skillexcept AttributeError as e: logging.exception(e)
ERROR:root:'Hero' object has no attribute '__skill'Traceback (most recent call last): File "", line 5, in hero1.__skillAttributeError: 'Hero' object has no attribute '__skill'
���������������������������������������������������������������������������������������������������������������������������������
���������������������������������name
���skill
���������������������Hero
���������get_name
���get_skill
������������������
class Hero(object): def __init__(self, name, skill): self.__name = name self.__skill = skill def say_hi(self): print(f'������������������{self.__name}���������{self.__skill}') def get_name(self): return self.__name def get_skill(self): return self.__skill
hero1 = Hero('���������', '���������������')hero1.get_skill()
'���������������'
������������������������������������skill
������������������������Hero
���������set_skill
���������
class Hero(object): def __init__(self, name, skill): self.__name = name self.__skill = skill def say_hi(self): print(f'������������������{self.__name}���������{self.__skill}') def get_name(self): return self.__name def get_skill(self): return self.__skill def set_skill(self, skill): self.__skill = skill
hero1 = Hero('���������', '���������������')hero1.set_skill('������������')hero1.get_skill()
'������������'
������������������������Python���������������������__xxx__
���������������������������������������������������������������������������������������������������������������������������������������private
���������������������������__name__
���__skill__
���������������������
������������������������������������������������������������������������������_name
���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������
���������������������������������������������������������������������������
������������������������������������__name
���������Python������������������__name
���������������_Hero__name
������������������������������_Hero__name
���������__name
���������
hero1._Hero__name
'���������'
������������������������������������������������������������Python���������������������__name
���������������������������
���������������������Python������������������������������������������������������������������
������������������������������������������
hero1 = Hero('���������', '���������������')hero1.get_name()
'���������'
hero1.__name = '���������'hero1.__name
'���������'
���������������������������������������������������__name
���������������������������__name
���������class���������__name
������������������������������������__name
���������������Python������������������������_Hero__name
���������������������������������������������__name
������������������������
hero1.get_name()
'���������'
hero1._Hero__name = '���������'hero1.get_name()
'���������'
���������������
���OOP
���������������������������������������class
������������������������������������class
���������������class���������������Subclass
���������������������class���������������������������������Base class
���Super class
������
������������������������������������������Animal
���class������������run()
���������������������������
class Animal(object): def run(self): print('Animal is running...')
���������������������Dog
���Cat
���������������������������Animal
������������
class Dog(Animal): passclass Cat(Animal): pass
������Dog
���������Animal
���������������������������Animal
���������Dog
���������������������
���������������������������������������������������������������������������������������Animial
���������run()
������������������Dog
���Cat
������������������������������������������������������������run()
���������
a1 = Dog()a2 = Cat()a1.run()a2.run()
Animal is running...Animal is running...
������������������������������������������������������������������������������������������Dog
������Cat
���������run()
���������������������������Animal is running...
���������������������������������������Dog is running...
���Cat is running...
���������������Dog
���Cat
������������������
class Dog(Animal): def run(self): print('Dog is running...')class Cat(Animal): def run(self): print('Cat is running...')
������������������������������
a1 = Dog()a2 = Cat()a1.run()a2.run()
Dog is running...Cat is running...
������������������������������������run()
���������������������������������run()
������������������run()
������������������������������������������������������run()
������������������������������������������������������������������
������������������������������������������������isinstance()
���������
isinstance(a1, Animal)
True
isinstance(a1, Dog)
True
������������������������������������������������Animal
������������������������������������������������������������������������run()
���������������������������run()
������������������Animal
���Dog
���Cat
���������������������������������������������������������������������������������������������������������������������������������������������������������������������������Animal
���������������������������run()
������������������������������������������������������������������������������������������������
���
������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������
���������������������
���������������������������������������������������������������������������������������
������������������������������������������������������������������������������������������������������������������������������������������������������object
������������������������������
���������������������������Java
������������������������������Animal
������������������������������������Animal
���������������������������������������������������run()
���������
������Python������������������������������������������������������Animal
������������������������������������������������������run()
���������������������
���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������
������������������
���������������������������������������������������������������������������������������������������
���������������������������type()
���������
type(1024)
int
type('���������')
str
type(None)
NoneType
type(abs)
builtin_function_or_method
type(a1)
__main__.Dog
type(a2)
__main__.Cat
type(1024) == int
True
import typestype(lambda x: x) == types.LambdaType
True
������class
������������������������������type()
���������������������������������class������������������������isinstance()
���������
isinstance(a2, Animal)
True
isinstance(a2, Cat)
True
isinstance(1024, int)
True
isinstance('���������', str)
True
isinstance([], list)
True
���������������������������������������������������������������
isinstance([1, 2, 3], (list, tuple))
True
isinstance({1, 2, 3}, (set, dict))
True
isinstance(a1, (Dog, Cat))
True
������isinstance()
���������������������������������������������������������������������
������������������������������������������������������������������dir()
������������������������������������������list
������������������������str
���������������������������������
dir(a1)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'run']
dir(Dog)
['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'run']
������__xxx__
���������������������Python������������������������������������__len__
������������������������Python���������������������len()
���������������������������������������������������������len()
���������������������������������������������__len__()
������
len('���������')
3
'���������'.__len__()
3
���������������������������������len(myObj)
���������������������������__len__()
������
class MyDog(object): def __len__(self): return 100 len(MyDog())
100
������������������������������������������������������getattr()
���setattr()
������hasattr()
���������������������������������������������������������������������Java������Golang���������������������������
hero = Hero('���������', '������������')# ���������'_Hero__name'������hasattr(hero, '_Hero__name')
True
# ���������'wife'������hasattr(hero, 'wife')
False
# ������������������'wife'setattr(hero, 'wife', '���������')# ���������'wife'������hasattr(hero, 'wife')
True
# ������������'wife'getattr(hero, 'wife')
'���������'
������������������������������
hasattr(hero, 'say_hi')
True
hi = getattr(hero, 'say_hi')hi
>
hi()
������������������������������������������������
���������������������������������������������������������������������������������������������������������������������������������������������������������������
def readImage(fp): if hasattr(fp, 'read'): return readData(fp) return None
������������������������
������������������������������������������������������������������self
���������
������Hero
������������������������������������������������class
������������������������������������������������Hero
������������
class Hero(object): book = '���������������' count = 0 def __init__(self, name, skill): self.name = name self.skill = skill Hero.count += 1 def say_hi(self): print(f'������������������{self.name}���������{self.skill}')
Hero.book
'���������������'
Hero.count
0
���������������������������������������������������������������������������
hero = Hero('������', '���������������')
hero.book
'���������������'
hero.count
1
# ���������������book������hero.book = '������������'# ������������������������������������������,������������������book������hero.book
'������������'
# ������������������������Hero.book
'���������������'
# ���������������book������del hero.book# ���������������book���������������������������book������������������������hero.book
'���������������'
������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������
������slots
���������������class
���������������������������������������������������������������������������������������������������������
���������������������������������������������������������������������������������Hero
������������name
���skill
���������
������������������������������Python���������������class
���������������������������������__slots__
���������������������class
���������������������������
class Hero(object): # ���tuple��������������������������������� __slots__ = ('name', 'skill') def __init__(self, name): self.name = name
hero = Hero('������')hero.skill = '���������������'hero.skill
'���������������'
import loggingtry: hero.wife = '���������'except AttributeError as e: logging.exception(e)
ERROR:root:'Hero' object has no attribute 'wife'Traceback (most recent call last): File "", line 4, in hero.wife = '���������'AttributeError: 'Hero' object has no attribute 'wife'
������wife
���������������__slots__
������������������������wife
���������������������wife
���������AttributeError
������������
������__slots__
������������__slots__
���������������������������������������������������������������������������������������
class ChineseHero(Hero): passh = ChineseHero('���������')h.country = '������'h.country
'������'
���������������������������__slots__
������������������������������������������������������������__slots__
���������������__slots__
���
������@property
������������������������������������������������������������������������������������������������������������������������������������������������������������
hero = Hero('������')hero.name = '������'hero.name
'������'
������������������������������������������
- ������������������������������������������������
set_xxx()
������������ - ������������������������������������������������������
set_xxx()
���������������������������������������get_xxx()
������������������������������set_xxx()
���������������������������������
������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������
���������������������decorator
������������������������������������������������������������������������������������������Python���������@property
������������������������������������������������
������������
class Hero(object): def __init__(self, name): self._name = name @property def name(self): return self._name @property def wife(self): return self._wife @wife.setter def wife(self, value): if len(value) == 0: print("wife������������") else: self._wife = value
@property
���������������getter
���������������������@xxx.setter
���������setter
���������������������������������������������������������������������������
hero = Hero('���������')# ���������������hero.get_name()hero.name
'���������'
try: hero.name = '���������'except AttributeError as e: print(e)
can't set attribute
name
���������������������������
# ���������������hero.set_wife('')hero.wife = ''
wife������������
hero.wife = '���������'hero.wife
'���������'
wife
���������������������������������������������������������������������������
@property
���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������
������������
������������������������������������������������������������������������������������������������������������������
class Animal(object): def say_hi(self): print('hi, Animal...')
������������������������������������Runnable
���Flyable
���������������������������������Runnable
���Flyable
���������
class Runnable(object): def run(self): print('Running...')class Flyable(object): def fly(self): print('Flying...')
������������Runnable
������������������������������������Runnable
���������Dog
���
class Dog(Animal, Runnable): passdog = Dog()dog.say_hi()dog.run()
hi, Animal...Running...
������������Flyable
������������������������������������Flyable
���������Bird
���
class Bird(Animal, Flyable): passbird = Bird()bird.say_hi()bird.fly()
hi, Animal...Flying...
������������������������������������������������������������������������������������
���������������������������������������������������������������������������������������Bird
���������Animal
������������������������������
������������������������������������������������������������������Bird
���������������Animal
���������������������Flyable
������������������������������MixIn
���
���������������������������������������������Runnable
���Flyable
������RunnableMixIn
���FlyableMixIn
���
MixIn
������������������������������������������������������������������������������������������������������������������������������������MixIn
���������������������������������������������������������������
Python������������������������������MixIn
������������������Python���������TCPServer
���UDPServer
���������������������������������������������������������������������������������������������������������������������ForkingMixIn
���ThreadingMixIn
���������������������������������������������������������������������
���������������������������������������TCP
������������������������
from socketserver import TCPServerfrom socketserver import ForkingMixInclass MyTCPServer(TCPServer, ForkingMixIn): pass
������������������������������UDP
������������������������
from socketserver import UDPServerfrom socketserver import ThreadingMixInclass MyUDPServer(UDPServer, ThreadingMixIn): pass
������������������������������������������������������������������������������������������������������������������������������������������������
���������
������������__slots__
������������__xxx__
������������������������������������������������Python���������������������������
__slots__
���������������������������������__len__()
������������������������������������class���������len()
���������
���������������Python���class������������������������������������������������������������������������������
__str__
���������������Hero
���������������������������
class Hero(object): def __init__(self, name): self.name = name print(Hero('���������'))
<__main__.Hero object at 0x113646a60>
���������������<__main__.Hero object at 0x...>
���������������
���������������������������������������������������__str__()
������������������������������������������������������
class Hero(object): def __init__(self, name): self.name = name def __str__(self): return f'Hero object (name: {self.name})' print(Hero('���������'))
Hero object (name: ���������)
���������������������������������������������������������������������������������������������
���������������������������������������������������print
������������������������������������������
Hero('���������')
<__main__.Hero at 0x113661700>
���������������������������������������������__str__()
���������__repr__()
���������������������__str__()
������������������������������������__repr__()
���������������������������������������������������������__repr__()
������������������������
������������������������������__repr__()
���������������__str__()
���__repr__()
���������������������������������������������������������
class Hero(object): def __init__(self, name): self.name = name def __str__(self): return f'Hero object (name: {self.name})' __repr__ = __str__ Hero('���������')
Hero object (name: ���������)
__iter__
���������������������������for ... in
���������������list
���tuple
������������������������������__iter__()
������������������������������������������������������Python���for������������������������������������������__next__()
������������������������������������������������StopIteration
������������������������
���������������������������������������Fib
���������������������for
���������
class Fib(object): def __init__(self): # ������������������������a���b self.a, self.b = 0, 1 def __iter__(self): # ������������������������������������������������ return self def __next__(self): # ������������������ self.a, self.b = self.b, self.a + self.b # ��������������������� if self.a > 20: raise StopIteration() # ������������������ return self.a for n in Fib(): print(n)
11235813
__getitem__
Fib
������������������������for
���������������������list
���������������������������������list
���������������������������������������5
������������
try: Fib()[5]except TypeError as e: print(e)
'Fib' object is not subscriptable
���������������list
���������������������������������������������__getitem__()
���������
class Fib(object): def __getitem__(self, n): a, b = 1, 1 for x in range(n): a, b = b, a + b return a
f = Fib()
f[0]
1
f[5]
8
f[6]
13
������������������������������dict
���__getitem__()
������������������������������������key
���object
���������str
���
������������������__setitem__()
������������������������list
���dict
������������������������������������������__delitem__()
������������������������������������
���������������������������������������������������������������������Python���������list
���tuple
���dict
������������������������������������������������������������������������������������������������������������
__getattr__
���������������������������������������������������������������������������������������
������������������������������������������������������������Python������������������������������������������__getattr__()
���������������������������������������������������������������������������friend
���Python������������������������__getattr__(self, 'friend')
���������������������������������������������������������friend
���������
class Hero(object): def __init__(self, name): self.name = name def __getattr__(self, attr): if attr == 'friend': return '������������������������������������' elif attr == 'count': return lambda: 1024 hero = Hero('���������')
������������������������������:
hero.friend
'������������������������������������'
���������������������������������
hero.count()
1024
������������������������������������������������������������__getattr__
���������������������������__getattr__
������������
���������������������������������hero.xxx
������������None
������������������������������__getattr__
������������������None
���
print(hero.xxx)
None
���������������������������������������������������������������������������������������������������������������������
Python���class������������������������������������������������������������������������������������������������������������������������������������������������������������������������������Python������������������
���������������
Python������������Enum
���
from enum import EnumMonth = Enum('Month', ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))
������������������������Month
���������������������������������������Month.Jan
���������������������������������������������������������
for name, member in Month.__members__.items(): print(name, '=>', member, ',', member.value)
Jan => Month.Jan , 1Feb => Month.Feb , 2Mar => Month.Mar , 3Apr => Month.Apr , 4May => Month.May , 5Jun => Month.Jun , 6Jul => Month.Jul , 7Aug => Month.Aug , 8Sep => Month.Sep , 9Oct => Month.Oct , 10Nov => Month.Nov , 11Dec => Month.Dec , 12
value
���������������������������������int
������������������1
���������������
������������������������������������������������������Enum
������������������������
from enum import Enum, unique# @unique������������������������������������������������������@uniqueclass Weekday(Enum): # Sun���value������������0 Sun = 0 Mon = 1 Tue = 2 Wed = 3 Thu = 4 Fri = 5 Sat = 6
���������������������������������������������������
Weekday.Mon
Weekday['Mon']
Weekday.Mon.value
1
Weekday(1)
���������������������������������������������������������������������������value
���������������������������
������������
���������������������������������������������������������������������������������������������������������������������������������������
������type()
������������������������������������Hero
���class���������������hero.py
������������Python���������������hero������������������������������������������������������������������������������������������������Hero
���class���������
hero = Hero('���������')
print(type(hero))
print(type(Hero))
type()
���������������������������������������������������Hero
���������class
���������������������type
������hero
������������������������������������class Hero
���
���������class������������������������������������������������class���������������������type()
���������
type()
���������������������������������������������������������������������������������������������������������type()
���������������Hello
���������������������class Hello(object)...
���������
# ���������������def fn(self, name='world'): print('Hello, %s.' % name)# ������Hello classHello = type('Hello', (object,), dict(hello=fn))h = Hello()h.hello()
Hello, world.
print(type(Hello))
print(type(h))
���������������class
���������type()
������������������3������������
- class������������
- ������������������������������Python���������������������������������������������������������tuple���������������������
- class������������������������������������������������������fn������������������hello���
������type()
������������������������������class
���������������������������Python���������������class
���������������������������������class
������������������������������type()
���������������class
���
������������������������������class Xxx...
������������������������type()
���������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������������
������metaclass
������������type()
���������������������������������������������������������������������metaclass
���
metaclass
���������������������������������������������
��������������������������������������������������������������������������������������������������������������������� ���������������������������������������������������������
metaclass
���������������������������������metaclass
��������������������� ������������������������������metaclass
���������������������������������������������
���������metaclass
���������������������������������������������������������������������������metaclass
������������������������������
������������������������������������metaclass
���������������������������MyList
������������add
���������
������ListMetaclass
������������������������metaclass
������������������Metaclass
������������������������������������������metaclass
���
# metaclass���������������������������������`type`���������������class ListMetaclass(type): def __new__(cls, name, bases, attrs): attrs['add'] = lambda self, value: self.append(value) return type.__new__(cls, name, bases, attrs)
������ListMetaclass
������������������������������������������������ListMetaclass
������������������������������������metaclass
���
class MyList(list, metaclass=ListMetaclass): pass
������������������������������metaclass
������������������������������������Python������������������MyList
���������������ListMetaclass.__new__()
������������������������������������������������������������������������������������������������������������������������
__new__()
������������������������������������
- ������������������������������������
- ���������������
- ���������������������������
- ���������������������
������������MyList
������������������add()
���������
L = MyList()L.add(1)L.add(0)L.add(2)L.add(4)L
[1, 0, 2, 4]
���������������������������������������MyList
���������������add()
������������������������������������������������������������������������������������������������������metaclass
���������������������
������������������������������������Java���������������������������������Java������������������������������������������������������Python���������������������������Java������������������������������������������
发表评论
最新留言
关于作者
