Python å¤å¿åæ¯ Python 3 ç¼ç¨è¯è¨çå页åè表
>>> print("Hello, World!")
Hello, World!
èåçâHello Worldâç¨åºå¨ Python ä¸çå®ç°
age = 18 # 年龿¯ int ç±»å
name = "John" # ååç°å¨æ¯ str ç±»å
print(name)
åºåæä¸æ¹æåºçå ç´ ï¼éåæä¸æ¹æ åºä¸ä¸éå¤çå ç´
| :- | :- |
|---|---|
str | ææ¬ï¼å符串ï¼Textï¼ |
int, float, complex | æ°å¼ï¼Numericï¼ |
dict | æ å°ï¼é®å¼å¯¹ï¼Mappingï¼ |
list, tuple, range | åºåï¼Sequenceï¼ |
set, frozenset | éåï¼Setï¼ |
bool | å¸å°å¼ï¼é»è¾å¼ï¼Booleanï¼ |
bytes, bytearray, memoryview | äºè¿å¶æ°æ®ï¼Binaryï¼ |
æ¥ç: æ°æ®ç±»å
>>> msg = "Hello, World!"
>>> print(msg[2:5])
llo
æ¥ç: å符串
mylist = []
mylist.append(1)
mylist.append(2)
for item in mylist:
print(item) # æå°è¾åº 1,2
æ¥ç: å表
num = 200
if num > 0:
print("num is greater than 0")
else:
print("num is not greater than 0")
æ¥ç: 夿
for item in range(6):
if item == 3: break
print(item)
else:
print("Finally finished!")
æ¥ç: 循ç¯
>>> def my_function():
... print("æ¥èªå½æ°çä½ å¥½")
...
>>> my_function()
æ¥èªå½æ°çä½ å¥½
æ¥ç: 彿°
with open("myfile.txt", "r", encoding='utf8') as file:
for line in file:
print(line)
æ¥ç: æä»¶å¤ç
result = 10 + 30 # => 40
result = 40 - 10 # => 30
result = 50 * 5 # => 250
result = 16 / 4 # => 4.0 (Float Division)
result = 16 // 4 # => 4 (Integer Division)
result = 25 % 2 # => 1
result = 5 ** 3 # => 125
/ 表示 x å y çåï¼// 表示 x å y çåºåï¼å¦è§ StackOverflow
counter = 0
counter += 10 # => 10
counter = 0
counter = counter + 10 # => 10
message = "Part 1."
# => Part 1.Part 2.
message += "Part 2."
>>> website = 'Quick Reference'
>>> f"Hello, {website}"
"Hello, Quick Reference"
>>> num = 10
>>> f'{num} + 10 = {num + 10}'
'10 + 10 = 20'
æ¥ç: f-å符串
hello = "Hello World"
hello = 'Hello World'
multi_string = """Multiline Strings
Lorem ipsum dolor sit amet,
consectetur adipiscing elit """
æ¥ç: å符串
x = 1 # æ´æ°
y = 2.8 # æµ®ç¹å°æ°
z = 1j # 夿°
>>> print(type(x))
<class 'int'>
åªè¦å åè¶³å¤ï¼å¯ä»¥å®¹çº³æ é大(å°)çæ°å¼
my_bool = True
my_bool = False
bool(0) # => False
bool(1) # => True
bool æ¯ int çåç±»
list1 = ["apple", "banana", "cherry"]
list2 = [True, False, False]
list3 = [1, 5, 7, 9, 3]
list4 = list((1, 5, 7, 9, 3))
æ¥ç: å表
my_tuple = (1, 2, 3)
my_tuple = tuple((1, 2, 3))
类似å表ï¼ä½èªèº«ä¸å¯å
set1 = {"a", "b", "c"}
set2 = set(("a", "b", "c"))
类似å表ï¼ä½éé¢çå ç´ æ¯æ åºèä¸éå¤ç
>>> empty_dict = {}
>>> a = {"one": 1, "two": 2, "three": 3}
>>> a["one"]
1
>>> a.keys()
dict_keys(['one', 'two', 'three'])
>>> a.values()
dict_values([1, 2, 3])
>>> a.update({"four": 4})
>>> a.keys()
dict_keys(['one', 'two', 'three', 'four'])
>>> a['four']
4
é®-å¼å¯¹ï¼ä¸ç§å JSON 飿 ·å¯¹è±¡
x = int(1) # å¾å° 1
y = int(2.8) # å¾å° 2
z = int("3") # å¾å° 3
x = float(1) # å¾å° 1.0
y = float(2.8) # å¾å° 2.8
z = float("3") # å¾å° 3.0
w = float("4.2") # å¾å° 4.2
x = str("s1") # å¾å° "s1"
y = str(2) # å¾å° "2"
z = str(3.0) # å¾å° "3.0"
>>> hello = "Hello, World"
>>> print(hello[1]) # è·å第äºä¸ªå符
e
>>> print(hello[-1]) # è·ååæ°ç¬¬ä¸ä¸ªå符
d
>>> print(type(hello[-1])) # å¾å°çè¿æ¯å符串
<class 'str'>
>>> for char in "foo":
... print(char)
f
o
o
对å符串 for-in å¯ä»¥å¾å°æ¯ä¸ªå符ï¼ç±»åè¿æ¯å符串ï¼
âââââ¬ââââ¬ââââ¬ââââ¬ââââ¬ââââ¬ââââ
| m | y | b | a | c | o | n |
âââââ´ââââ´ââââ´ââââ´ââââ´ââââ´ââââ
0 1 2 3 4 5 6 7
-7 -6 -5 -4 -3 -2 -1
>>> s = 'mybacon'
>>> s[2:5]
'bac'
>>> s[0:2]
'my'
>>> s = 'mybacon'
>>> s[:2]
'my'
>>> s[2:]
'bacon'
>>> s[:2] + s[2:]
'mybacon'
>>> s[:]
'mybacon'
>>> s = 'mybacon'
>>> s[-5:-1]
'baco'
>>> s[2:6]
'baco'
>>> s = '12345' * 5
>>> s
'1234512345123451234512345'
>>> s[::5]
'11111'
>>> s[4::5]
'55555'
>>> s[::-5]
'55555'
>>> s[::-1]
'5432154321543215432154321'
>>> hello = "Hello, World!"
>>> print(len(hello))
13
len() 彿°è¿åå符串çé¿åº¦
>>> s = '===+'
>>> n = 8
>>> s * n
'===+===+===+===+===+===+===+===+'
>>> s = 'spam'
>>> s in 'I saw spamalot!'
True
>>> s not in 'I saw The Holy Grail!'
True
夿 "spam" è¿ä¸ªå符串æ¯å¦å¨å ¶å®å符串é
>>> s = 'spam'
>>> t = 'egg'
>>> s + t # å¯ä»¥ä½¿ç¨å å·è¿è¡æ¼æ¥
'spamegg'
>>> 'spam' 'egg' # 两个å符串ä¹é´å¯ä»¥çç¥å å·
'spamegg'
name = "John"
print("Hello, %s!" % name)
name = "John"
age = 23
print("%s is %d years old." % (name, age))
txt1 = "My name is {fname}, I'm {age}".format(fname="John", age=36)
txt2 = "My name is {0}, I'm {1}".format("John", 36)
txt3 = "My name is {}, I'm {}".format("John", 36)
| 转ä¹ç¬¦å· | 对åºçæä½ |
|---|---|
\\ | è¾åºåææ |
\' | è¾åºåå¼å· |
\" | è¾åºåå¼å· |
\n | æ¢è¡ |
\t | æ°´å¹³å¶è¡¨ç¬¦ |
\r | å æ åå°é¦ä½ |
\b | éæ ¼ |
>>> name = input("Enter your name: ")
Enter your name: Tom
>>> name
'Tom'
仿§å¶å°è·åè¾å ¥æ°æ®
>>> # æ¯å¦ä»¥ H å¼å¤´
>>> "Hello, world!".startswith("H")
True
>>> # æ¯å¦ä»¥ h å¼å¤´
>>> "Hello, world!".startswith("h")
False
>>> # æ¯å¦ä»¥ ! ç»å°¾
>>> "Hello, world!".endswith("!")
True
>>> "ã".join(["John", "Peter", "Vicky"])
'JohnãPeterãVicky'
>>> website = 'Reference'
>>> f"Hello, {website}"
"Hello, Reference"
>>> num = 10
>>> f'{num} + 10 = {num + 10}'
'10 + 10 = 20'
>>> f"""He said {"I'm John"}"""
"He said I'm John"
>>> f'5 {"{stars}"}'
'5 {stars}'
>>> f'{{5}} {"stars"}'
'{5} stars'
>>> name = 'Eric'
>>> age = 27
>>> f"""Hello!
... I'm {name}.
... I'm {age}."""
"Hello!\n I'm Eric.\n I'm 27."
å®ä» Python 3.6 å¼å§å¯ç¨ï¼å¦è§: æ ¼å¼å符串åé¢å¼
>>> f'{"text":10}' # 使ç¨ç©ºæ ¼å¡«å
å°æå®é¿åº¦
'text '
>>> f'{"test":*>10}' # å左填å
'******test'
>>> f'{"test":*<10}' # åå³å¡«å
'test******'
>>> f'{"test":*^10}' # å±
ä¸å¡«å
'***test***'
>>> f'{12345:0>10}' # ä½¿ç¨æ°åå¡«å
'0000012345'
>>> f'{10:b}' # è¾åºäºè¿å¶æ°å¼
'1010'
>>> f'{10:o}' # è¾åºå
«è¿å¶æ°å¼
'12'
>>> f'{200:x}' # è¾åºåå
è¿å¶æ°å¼
'c8'
>>> f'{200:X}'
'C8'
>>> f'{345600000000:e}' # ç§å¦è®¡æ°æ³
'3.456000e+11'
>>> f'{65:c}' # å°æ´æ°è½¬å为ä¸ä¸ªå符åè¾åº
'A'
>>> f'{10:#b}' # [ç±»å] 带符å·ï¼åºç¡ï¼
'0b1010'
>>> f'{10:#o}'
'0o12'
>>> f'{10:#x}'
'0xa'
>>> f'{12345:+}' # æ¾ç¤ºæ£æ°çæ£å·
'+12345'
>>> f'{-12345:+}' # æ¾ç¤ºè´æ°çè´å·
'-12345'
>>> f'{-12345:+10}' # æ¾ç¤ºè´å·ï¼å¹¶ä½¿ç¨ç©ºæ ¼å¡«å
ï¼ç´å°é¿åº¦ä¸º 10
' -12345'
>>> f'{-12345:+010}' # æ¾ç¤ºè´å·ï¼å¹¶ä½¿ç¨0å¡«å
ï¼ç´å°é¿åº¦ä¸º 10
'-000012345'
>>> f'{-12345:0=10}' # è´æ°
'-000012345'
>>> f'{12345:010}' # [0] å¿«æ·æ¹å¼ï¼ä¸å¯¹é½ï¼
'0000012345'
>>> f'{-12345:010}'
'-000012345'
>>> import math # [.precision]
>>> math.pi
3.141592653589793
>>> f'{math.pi:.2f}'
'3.14'
>>> f'{1000000:,.2f}' # [åç»é项]
'1,000,000.00'
>>> f'{1000000:_.2f}'
'1_000_000.00'
>>> f'{0.25:0%}' # ç¾åæ¯
'25.000000%'
>>> f'{0.25:.0%}'
'25%'
>>> li1 = []
>>> li1
[]
>>> li2 = [4, 5, 6]
>>> li2
[4, 5, 6]
>>> li3 = list((1, 2, 3))
>>> li3
[1, 2, 3]
>>> li4 = list(range(1, 11))
>>> li4
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list(filter(lambda x : x % 2 == 1, range(1, 20)))
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
>>> [x ** 2 for x in range (1, 11) if x % 2 == 1]
[1, 9, 25, 49, 81]
>>> [x for x in [3, 4, 5, 6, 7] if x > 5]
[6, 7]
>>> list(filter(lambda x: x > 5, [3, 4, 5, 6, 7]))
[6, 7]
>>> li = []
>>> li.append(1)
>>> li
[1]
>>> li.append(2)
>>> li
[1, 2]
>>> li.append(4)
>>> li
[1, 2, 4]
>>> li.append(3)
>>> li
[1, 2, 4, 3]
å表åççè¯æ³ï¼
a_list[start:end]
a_list[start:end:step]
>>> a = ['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a[2:5]
['bacon', 'tomato', 'ham']
>>> a[-5:-2]
['egg', 'bacon', 'tomato']
>>> a[1:4]
['egg', 'bacon', 'tomato']
>>> a[:4]
['spam', 'egg', 'bacon', 'tomato']
>>> a[0:4]
['spam', 'egg', 'bacon', 'tomato']
>>> a[2:]
['bacon', 'tomato', 'ham', 'lobster']
>>> a[2:len(a)]
['bacon', 'tomato', 'ham', 'lobster']
>>> a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a[:]
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a[0:6:2]
['spam', 'bacon', 'ham']
>>> a[1:6:2]
['egg', 'tomato', 'lobster']
>>> a[6:0:-2]
['lobster', 'tomato', 'egg']
>>> a
['spam', 'egg', 'bacon', 'tomato', 'ham', 'lobster']
>>> a[::-1]
['lobster', 'ham', 'tomato', 'bacon', 'egg', 'spam']
>>> li = ['bread', 'butter', 'milk']
>>> li.pop()
'milk'
>>> li
['bread', 'butter']
>>> del li[0]
>>> li
['butter']
>>> li.remove('butter')
>>> li
[]
>>> li = ['a', 'b', 'c', 'd']
>>> li[0]
'a'
>>> li[-1]
'd'
>>> li[4]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> odd = [1, 3, 5]
>>> odd.extend([9, 11, 13])
>>> odd
[1, 3, 5, 9, 11, 13]
>>> odd = [1, 3, 5]
>>> odd + [9, 11, 13]
[1, 3, 5, 9, 11, 13]
>>> li = [3, 1, 3, 2, 5]
>>> li.sort()
>>> li
[1, 2, 3, 3, 5]
>>> li.reverse()
>>> li
[5, 3, 3, 2, 1]
>>> li = [3, 1, 3, 2, 5]
>>> li.count(3)
2
>>> li = ["re"] * 3
>>> li
['re', 're', 're']
>>> nums = [40, 36, 89, 2, 36, 100, 7, -20.5, -999]
>>> nums.index(2)
3
>>> nums.index(100, 3, 7) # æç´¢3-7ä¹é´çå
ç´
5
>>> nums.index(7, 4) # æç´¢4ä¹åçå
ç´
6
å½å¯»æ¾ä¸ä¸ªä¸åå¨ç弿¶ï¼æåºValueErrorã
number = int(input('è¾å
¥ä¸ä¸ªæ´æ°ï¼'))
if number < 0:
print("æ¨è¾å
¥äºä¸ä¸ªè´æ°ã")
else:
print("æ¨è¾å
¥äºä¸ä¸ªéè´æ´æ°ã")
number = int(input('è¾å
¥ä¸ä¸ªæ´æ°ï¼'))
if number < 0:
print("æ¨è¾å
¥äºä¸ä¸ªè´æ°ã")
elif number == 0:
print("æ¨è¾å
¥äºä¸ä¸ª 0 ã")
else:
print("æ¨è¾å
¥äºä¸ä¸ªæ£æ°ã")
scope = int(input('è¾å
¥ç¾åå¶æç»©ï¼'))
line = 60
tip = "åæ ¼" if scope >= line else "ä¸åæ ¼"
# ç¸å½äº scope >= line ? "åæ ¼" : "ä¸åæ ¼"
print(tip)
æ³¨ææ¡ä»¶æ¯æ¾å¨ä¸é´ç
primes = [2, 3, 5, 7]
for prime in primes:
print(prime)
animals = ["dog", "cat", "mouse"]
for i, value in enumerate(animals):
print(i, value)
x = 0
while x < 4:
print(x)
x += 1 # Shorthand for x = x + 1
x = 0
for index in range(10):
x = index * 10
if index == 5:
break
print(x)
for index in range(3, 8):
x = index * 10
if index == 5:
continue
print(x)
for i in range(4):
print(i) # Prints: 0 1 2 3
for i in range(4, 8):
print(i) # Prints: 4 5 6 7
for i in range(4, 10, 2):
print(i) # Prints: 4 6 8
name = ['Pete', 'John', 'Elizabeth']
age = [6, 23, 44]
for n, a in zip(name, age):
print('%s is %d years old' %(n, a))
result = [x**2 for x in range(10) if x % 2 == 0]
print(result)
# [0, 4, 16, 36, 64]
def hello_world():
print('Hello, World!')
def add(x, y):
print("x is %s, y is %s" %(x, y))
return x + y
add(5, 6) # => 11
def varargs(*args):
return args
varargs(1, 2, 3) # => (1, 2, 3)
args çç±»åæ¯ tuple
def keyword_args(**kwargs):
return kwargs
# => {"big": "foot", "loch": "ness"}
keyword_args(big="foot", loch="ness")
kwargs çç±»åæ¯ dict
def swap(x, y):
return y, x
x = 1
y = 2
x, y = swap(x, y) # => x = 2, y = 1
def add(x, y=10):
return x + y
add(5) # => 15
add(5, 20) # => 25
# => True
(lambda x: x > 2)(3)
# => 5
(lambda x, y: x ** 2 + y ** 2)(2, 1)
_ è¿ä¸ªå鿝å½ä»¤è¡äº¤äºä¸æå䏿¬¡è®¡ç®å¾å°çå¼ï¼å¨ç¨åºè®¾è®¡ä¸ä¸è¬ç¨æ¥åæ¾è§£å
æ¶ä¸åéè¦çå¼ã
ä½å®çå«ä¹ä¼å èµå¼èæ¹åï¼æ¯å¦æ ååº gettext ä¸å¸¸ç¨ä½å¨æè·åç¿»è¯ææ¬ãip, port = "127.0.0.1", 80
print(ip) # -> "127.0.0.1"
print(port) # -> 80
# ä¸ä»¥ä¸ä»£ç çä»·
ip, port = ("127.0.0.1", 80)
# ä¸ä»¥ä¸ä»£ç ææç¸å
ip, port = ["127.0.0.1", 80]
ip, _, port = "127.0.0.1:80".rpartition(":")
print(ip) # -> "127.0.0.1"
print(port) # -> "80"
# _ è¿ä¸ªå鿤å»ç弿¯ ":" ï¼ä½ä¸è¬ä¸å使ç¨ã
_ 乿¯ä¸ä¸ªåä¸åéï¼ä¸å
许解å
å¤ä¸ªå
ç´ ï¼å æ¤åéä¸å¼å¿
é¡»ä¸ä¸å¯¹åºã
major, minor, *parts = "3.10.2.beta".split(".")
print(major) # -> "3"
print(minor) # -> "10"
print(parts) # -> ["2", "beta"]
# å¯å° parts æ¹ä¸º _ æ¥è¡¨ç¤ºä¸åéè¦åé¢çå
ç´
è¿éç * å°±æ¯æ¶éåºåå¨è§£å
è¿ç¨ä¸å¤åºæ¥çå
ç´ ï¼
åªè½æä¸ä¸ªï¼ä¸å彿°ä¼ éä½ç½®åæ°æ¶ç * 嫿 äºè´ã
major, minor, *_ = "3.10.2.beta".split(".")
print(major) # -> "3"
print(minor) # -> "10"
major, *_, level = "3.10.2.beta".split(".")
print(major) # -> "3"
print(level) # -> "beta"
*_, micro, level = "3.10.2.beta".split(".")
print(micro) # -> "2"
print(level) # -> "beta"
a, b, *_ = {3, 2, 1}
print(a) # -> 1
print(b) # -> 2
print(_) # -> [3]
éå ä¸çå ç´ æ¯æ åºçï¼å æ¤è§£å ç»æä¸è½è½»æç¡®å®ã
a, b, *_ = range(3)
print(a) # -> 0
print(b) # -> 1
print(_) # -> [2]
æ¯æ è¿ä»£å¨ åè®®ç对象ä¹å¯è¢«è§£å ã
a, b, *_ = dict(a=1, b=2, c=3)
print(a) # -> "a"
print(_) # -> ["c"]
a, b, *_ = dict(a=1, b=2, c=3).values()
print(a) # -> 1
print(_) # -> [3]
chars = (*"abc", *"def", "g", "h")
# -> ("a", "b", "c", "d", "e", "f", "g", "h")
digits = [*range(10), *"abcdef"]
# -> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
# "a", "b", "c", "d", "e", "f"]
part = {"å°æ": 18, "å°äº®": 22}
summary = {"å°è±": 16, **part}
print(summary)
# -> {"å°è±": 16, "å°æ": 18, "å°äº®": 22}
***students = [
("å°æ", 18),
("å°äº®", 22),
]
for k, v in students:
print(k) # -> "å°æ"ã"å°äº®"
print(v) # -> 18ã22
students = [
(0, ("å°æ", 18)),
(1, ("å°äº®", 22)),
]
for i, (k, v) in students:
print(i) # -> 0ã1
print(k) # -> "å°æ"ã"å°äº®"
print(v) # -> 18ã22
def version(major, minor, *parts):
print(major) # -> "3"
print(minor) # -> "10"
print(parts) # -> ("2", "beta", "0")
version("3", "10", "2", "beta", "0")
# è¿ç¨ç±»ä¼¼äº
major, minor, *parts = ("3", "10", "2", "beta", "0")
def version():
parts = "3.10.2.beta.0".split(".")
return *parts, "x64"
print(version())
# -> ("3", "10", "2", "beta", "0", "x64")
import math
print(math.sqrt(16)) # => 4.0
from math import ceil, floor
print(ceil(3.7)) # => 4.0
print(floor(3.7)) # => 3.0
from math import *
import math as m
# => True
math.sqrt(16) == m.sqrt(16)
import math
dir(math)
with open("myfile.txt") as file:
for line in file:
print(line)
file = open('myfile.txt', 'r')
for i, line in enumerate(file, start=1):
print("Number %s: %s" % (i, line))
contents = {"aa": 12, "bb": 21}
with open("myfile1.txt", "w+") as file:
file.write(str(contents))
with open('myfile1.txt', "r+") as file:
contents = file.read()
print(contents)
contents = {"aa": 12, "bb": 21}
with open("myfile2.txt", "w+") as file:
file.write(json.dumps(contents))
with open('myfile2.txt', "r+") as file:
contents = json.load(file)
print(contents)
import os
os.remove("myfile.txt")
import os
if os.path.exists("myfile.txt"):
os.remove("myfile.txt")
else:
print("The file does not exist")
import os
os.rmdir("myfolder")
class MyNewClass:
pass
# ç±»çå®ä¾å
my = MyNewClass()
class Animal:
def __init__(self, voice):
self.voice = voice
cat = Animal('Meow')
print(cat.voice) # => Meow
dog = Animal('Woof')
print(dog.voice) # => Woof
class Dog:
# ç±»çæ¹æ³
def bark(self):
print("Ham-Ham")
charlie = Dog()
charlie.bark() # => "Ham-Ham"
class MyClass:
class_variable = "A class variable!"
# => ä¸ä¸ªç±»åéï¼
print(MyClass.class_variable)
x = MyClass()
# => ä¸ä¸ªç±»åéï¼
print(x.class_variable)
class ParentClass:
def print_test(self):
print("Parent Method")
class ChildClass(ParentClass):
def print_test(self):
print("Child Method")
# è°ç¨ç¶çº§ç print_test()
super().print_test()
>>> child_instance = ChildClass()
>>> child_instance.print_test()
Child Method
Parent Method
class Employee:
def __init__(self, name):
self.name = name
def __repr__(self):
return self.name
john = Employee('John')
print(john) # => John
class CustomError(Exception):
pass
class ParentClass:
def print_self(self):
print('A')
class ChildClass(ParentClass):
def print_self(self):
print('B')
obj_A = ParentClass()
obj_B = ChildClass()
obj_A.print_self() # => A
obj_B.print_self() # => B
class ParentClass:
def print_self(self):
print("Parent")
class ChildClass(ParentClass):
def print_self(self):
print("Child")
child_instance = ChildClass()
child_instance.print_self() # => Child
class Animal:
def __init__(self, name, legs):
self.name = name
self.legs = legs
class Dog(Animal):
def sound(self):
print("Woof!")
Yoki = Dog("Yoki", 4)
print(Yoki.name) # => YOKI
print(Yoki.legs) # => 4
Yoki.sound() # => Woof!
å®ç°è®¡ç®å±æ§ãåªè¯»å±æ§åéªè¯é»è¾ã
class Person:
def __init__(self, age):
self._age = age # 约å®ï¼_age 为å
é¨å±æ§
@property
def age(self):
"""è·åå¹´é¾çæ¹æ³ï¼ä¼ªè£
æå±æ§"""
return self._age
@age.setter
def age(self, value):
"""设置年é¾çæ¹æ³ï¼æ·»å éªè¯é»è¾"""
if value < 0:
raise ValueError("å¹´é¾ä¸è½ä¸ºè´æ°")
self._age = value
# 使ç¨ç¤ºä¾
p = Person(30)
print(p.age) # ç´æ¥è®¿é®å±æ§ï¼æ éæ¬å· â 30
p.age = 31 # èµå¼æä½è°ç¨ @age.setter â éªè¯éè¿
p.age = -5 # æåº ValueError: å¹´é¾ä¸è½ä¸ºè´æ°
æ´å¤è¯·ç§»æ¥ https://docs.python.org/zh-cn/3/reference/datamodel.html
åè§ èªå®ä¹ç±»å建 ã
from typing import Any
class Object:
def __new__(cls, *args, **kwargs) -> "self":
# new å init 声æçåæ°å¿
é¡»ä¸è´
# æè
ç¨ *args å **kwargs è¿è¡å
¼å®¹
return object.__new__(cls)
def __init__(self, *args, **kwargs):
# åå§åæ¹æ³æ²¡æè¿åå¼ï¼ä¹ä¸è½è¿åå¼ã
pass
def __call__(self, *args, **kwargs) -> Any:
pass
# 便¬¡è°ç¨äº new å initï¼æä»¥å¦æ
# æå¨è°ç¨ newï¼é£ä¹å«å¿äºè°ç¨ init
obj = Object()
# 触å __call__ æ¹æ³ï¼è¦ç»ä»ä¹åæ°åå³äºå£°æ
obj()
åè§ ä¸ä¸æç®¡çå¨ ã
from typing import Any
class Object:
def __enter__(self) -> Optional[Any]:
# with è¯å¥ä¼å°è¿åå¼ç»å®å° as åå¥ä¸çåéï¼å¦ææçè¯ã
return
def __exit__(self, exc_type, exc_value, traceback):
# è¥ with å
没æåçå¼å¸¸ï¼åä¸ä¸ªåæ°é½æ¯ None ã
# ä¸åºè¯¥éæ°å¼åä¼ å
¥çå¼å¸¸ï¼è¿æ¯è°ç¨è
ç责任ã
pass
with Object() as alias:
# è¿å
¥ with ä¹åè°ç¨ obj.__enter__() å¹¶å¾å° aliasï¼å¦ææè¿åçè¯ï¼
pass
# ç¦»å¼ with åè°ç¨ obj.__exit__() ï¼ä¸ç®¡æ¯æ£å¸¸ç»æè¿æ¯å å¼å¸¸æåºè离å¼ã
# å½éè¦è·å Object ç对象æ¶å¯ä»¥è¿æ ·å
obj = Object()
with obj as alias:
pass
ä¸è¡¨ä½¿ç¨ -> * 代表è¿åå¼ç±»åæ¯ä»»æçï¼æè
éè¦è§æ
åµèå®ï¼å®é
ä¸å¹¶ä¸åå¨è¿ç§åæ³ã
è¯¸å¦ -> str ä»
表示ç»å¤§å¤æ°æ
åµä¸åºå½è¿å str ç±»åï¼æè
æ¨èè¿å str ç±»åã
没æ -> çæ¹æ³ä¸è¬æ²¡æè¿åå¼ã
åè§ https://docs.python.org/zh-cn/3/reference/datamodel.html
| è¯å¥ | ç¹æ®æ¹æ³ | 夿³¨ | |
|---|---|---|---|
repr(obj) | __repr__(self) -> str | è¯¦è§ repr() ã | |
str(obj) | __str__(self) -> str | è¯¦è§ str ç±»å ã | |
bytes(obj) | __bytes__(self) -> bytes | è¯¦è§ bytes() ã | |
format(obj, spec) | __format__(self, spec) -> str | è¯¦è§ format()ãæ ¼å¼åå符串åé¢å¼ãæ ¼å¼è§æ ¼è¿·ä½ è¯è¨ ã | |
hash(obj) | __hash__(self) -> int | è¯¦è§ hash() ã | |
bool(obj) | __bool__(self) -> bool | æªå®ä¹æ¶è°ç¨ obj.__len__() != 0 ï¼è¥ __len__() 乿ªå®ä¹ï¼åææå¯¹è±¡é½è¢«è§ä¸º True ãå¦è§ bool() ã | |
dir(obj) | __dir__(self) -> list | è¿åå¼å¿
é¡»æ¯ä¸ä¸ªåºåï¼dir() 伿è¿åçåºå转æ¢ä¸ºå表并对å
¶æåºã | |
Object[key] | __class_getitem__(cls, key) -> * | ä¸å»ºè®®ç¨äºé¤äº æ¨¡ææ³åç±»å 以å¤çç¨éï¼é¿å IDE 误å¤ã |
| è¯å¥ | ç¹æ®æ¹æ³ | 夿³¨ | |
|---|---|---|---|
isinstance(instance, class) | class.__instancecheck__(self, instance) -> bool | 妿 instance åºè¢«è§ä¸º class çä¸ä¸ªï¼ç´æ¥æé´æ¥ï¼å®ä¾åè¿åçå¼ã | |
issubclass(subclass, class) | class.__subclasscheck__(self, subclass) -> bool | 妿 subclass åºè¢«è§ä¸º class çä¸ä¸ªï¼ç´æ¥æé´æ¥ï¼åç±»åè¿åçå¼ã |
| è¯å¥ | ç¹æ®æ¹æ³ | 夿³¨ | |
|---|---|---|---|
obj < other | __lt__(self, other) -> bool | ||
obj <= other | __le__(self, other) -> bool | ||
obj == other | __eq__(self, other) -> bool | é»è®¤è¿å obj is other ï¼å¦æç»æä¸º False ï¼åä¼è¿å NotImplemented ã | |
obj != other | __ne__(self, other) -> bool | é»è®¤è¿å not obj.__eq__(other) ã | |
obj > other | __gt__(self, other) -> bool | ||
obj >= other | __ge__(self, other) -> bool |
| è¯å¥ | ç¹æ®æ¹æ³ | 夿³¨ | |
|---|---|---|---|
obj.name | __getattr__(self, name) -> * | ä¼å
è°ç¨ãå½æåº AttributeError æ¶è½¬åè°ç¨ __getattribute__() ã | |
obj.name | __getattribute__(self, name) -> * | åè§ èªå®ä¹å±æ§è®¿é® é¿å æ ééå½ã | |
obj.name = value | __setattr__(self, name, value) | ||
del obj.name | __delattr__(self, name) | ä»
å¨ del obj.name 对äºè¯¥å¯¹è±¡ææä¹æ¶æåºè¯¥è¢«å®ç°ã |
| è¯å¥ | ç¹æ®æ¹æ³ | 夿³¨ | |
|---|---|---|---|
len(obj) | __len__(self) -> int | ||
op.length_hint(obj) | __length_hint__(self) -> int | å¨ä½¿ç¨æ ååº operator ç length_hint() æ¶ä¼è¢«è°ç¨ï¼Python 3.4+ï¼ã | |
obj[key] | __getitem__(self, key) -> * | éè¦æåº IndexError 以便æ£ç¡®å°ç»æ for 循ç¯ã | |
obj[key] | __missing__(self, key) -> * | ä»
å¨ dict çåç±»æ¾ä¸å°é®æ¶è¢«è°ç¨ï¼ä¸è½éå __getitem__ æ¹æ³ï¼ã | |
obj[key] = value | __setitem__(self, key, value) | a[1:2] = b å®é
䏿¯ a[slice(1, 2, None)] = b ï¼å
¶å®æ
å½¢åå¨å
¶ä½æ¹æ³ä¸åçãè¯¦è§ slice() ã | |
del obj[key] | __delitem__(self, key) | ||
| è°ç¨é徿å¾å¤ | __iter__(self) -> Iterator | å¨éè¦å建ä¸ä¸ª è¿ä»£å¨ æ¶è¢«è°ç¨ï¼ä¾å¦ä½¿ç¨ iter() ã for å¾ªç¯ ãæå¥½è¿åä¸ä¸ªæ°å¯¹è±¡ï¼å 为è¿ä»£å¨å¨è¯ä¹ä¸æ¯ä¸æ¬¡æ§çãè¥è¿å self ï¼åå¿
é¡»å®ç° __next__() æ¹æ³ã | |
reversed(obj) | __reversed__(self) -> * | è¯¦è§ reversed() ã | |
item in obj | __contains__(self, item) -> bool | å¯¹äºæªå®ä¹è¯¥æ¹æ³çå¯¹è±¡å¨ in å not in æ¶ï¼åè æåæ£æµè¿ç® ã |
| è¯å¥ | ç¹æ®æ¹æ³ | 夿³¨ | |
|---|---|---|---|
+obj | __neg__(self) -> * | ||
-obj | __pos__(self) -> * | ||
~obj | __invert__(self) -> * | ||
abs(obj) | __abs__(self) -> * | ||
int(obj) | __int__(self) -> * | ||
float(obj) | __float__(self) -> * | ||
complex(obj) | __complex__(self) -> * | ||
round(obj) | __round__(self) -> int | è¯¦è§ round() ã | |
round(obj) | __round__(self, ndigits) -> * | è¯¦è§ round() ã | |
math.ceil(obj) | __ceil__(self) -> int | è¯¦è§æ ååº math ç ceil() ã | |
math.floor(obj) | __floor__(self) -> int | è¯¦è§æ ååº math ç floor() ã | |
math.trunc(obj) | __trunc__(self) -> int | è¯¦è§æ ååº math ç trunc() ã | |
__index__(self) -> int | éè¦æ æå°å°æ°å¼è½¬æ¢ä¸ºæ´æ°çæ¶åä¼è¢«è°ç¨ãè¯¦è§ è¿é ã | ||
obj + other | __add__(self, other) -> * | ||
obj - other | __sub__(self, other) -> * | ||
obj * other | __mul__(self, other) -> * | ||
obj @ other | __matmul__(self, other) -> * | ä¸ºç¬¬ä¸æ¹åºèççç©éµä¹æ³è¿ç®ç¬¦ï¼è¿éæäºä¸å´ãï¼Python 3.5+ï¼ | |
obj / other | __truediv__(self, other) -> * | ||
obj // other | __floordiv__(self, other) -> * | ||
obj % other | __mod__(self, other) -> * | ||
divmod(obj, other) | __divmod__(self, other) -> tuple | divmod(a, b) è¿åä¸ä¸ªå
ç» (a // b, a % b) ï¼è¯¦è§ divmod() ã | |
obj ** exp | __pow__(self, exp) -> * | ||
pow(obj, exp, mod) | __pow__(self, exp, mod) -> * | pow(base, exp, mod) æ¯ pow(base, exp) % mod æ´é«æã | |
obj << other | __lshift__(self, other) -> * | ||
obj >> other | __rshift__(self, other) -> * | ||
obj & other | __and__(self, other) -> * | ||
obj ^ other | __xor__(self, other) -> * | ||
obj | other | __or__(self, other) -> * | ||
other + obj | __radd__(self, obj) -> * | ä»
å½ obj æªå®ä¹ __add__() æå
¶è¿å NotImplemented ï¼ä¸ä¸ other äºç¸é½æ²¡æç»§æ¿å ³ç³»æ¶ï¼è°ç¨ other ç __radd__() ãè¯¦è§ è¿é ã | |
other - obj | __rsub__(self, obj) -> * | 以ä¸ï¼å¦æ¤ç±»æ¨ã | |
other * obj | __rmul__(self, obj) -> * | ||
other @ obj | __rmatmul__(self, obj) -> * | ||
other / obj | __rtruediv__(self, obj) -> * | ||
other // obj | __rfloordiv__(self, obj) -> * | ||
other % obj | __rmod__(self, obj) -> * | ||
divmod(other, obj) | __rdivmod__(self, obj) -> tuple | ||
other ** obj | __rpow__(self, obj) -> * | ||
__rpow__(self, obj, mod) -> * | pow(obj, other, mod) ä¸ä¼å°è¯è°ç¨ other.__rpow__(obj, mod) ï¼å 为强å¶è½¬æ¢è§åä¼å¤ªè¿å¤æã | ||
other << obj | __rlshift__(self, obj) -> * | ||
other >> obj | __rrshift__(self, obj) -> * | ||
other & obj | __rand__(self, obj) -> * | ||
other ^ obj | __rxor__(self, obj) -> * | ||
other | obj | __ror__(self, obj) -> * | ||
obj += other | __iadd__(self, other) -> * | è¥æ¹æ³å·²å®ä¹ï¼å a += b çä»·äº a.__iadd(b) ï¼è¥æªå®ä¹ï¼ååéå° a + b éæ© x.__add__(y) å y.__radd__(x) ã | |
obj -= other | __isub__(self, other) -> * | 以ä¸ï¼å¦æ¤ç±»æ¨ã | |
obj *= other | __imul__(self, other) -> * | ||
obj @= other | __imatmul__(self, other) -> * | ||
obj /= other | __itruediv__(self, other) -> * | ||
obj //= other | __ifloordiv__(self, other) -> * | ||
obj %= other | __imod__(self, other) -> * | ||
obj **= exp | __ipow__(self, other) -> * | ||
obj <<= other | __ilshift__(self, other) -> * | ||
obj >>= other | __irshift__(self, other) -> * | ||
obj &= other | __iand__(self, other) -> * | ||
obj ^= other | __ixor__(self, other) -> * | ||
obj |= other | __ior__(self, other) -> * |
string: str = "ha"
times: int = 3
print(string * times) # => hahaha
result: str = 1 + 2
print(result) # => 3
é误çç±»åæ æ³¨ä¸ä¼å½±åæ£å¸¸è¿è¡ï¼ä¹ä¸ä¼æ¥é
def say(name: str, start: str = "Hi"):
return start + ", " + name
print(say("Python")) # => Hi, Python
def calc_summary(*args: int):
return sum(args)
print(calc_summary(3, 1, 4)) # => 8
表示 args çææå ç´ é½æ¯ int ç±»åçã
def say_hello(name) -> str:
return "Hello, " + name
var = "Python"
print(say_hello(var)) # => Hello, Python
from typing import Union
def resp200(meaningful) -> Union[int, str]:
return "OK" if meaningful else 200
表示è¿åå¼å¯è½æ¯ intï¼ä¹å¯è½æ¯ str ã
def calc_summary(**kwargs: int):
return sum(kwargs.values())
print(calc_summary(a=1, b=2)) # => 3
表示 kwargs çææå¼é½æ¯ int ç±»åçã
def resp200() -> (int, str):
return 200, "OK"
def resp200(meaningful) -> int | str:
return "OK" if meaningful else 200
èª Python 3.10 èµ·å¯ç¨ã
class Employee:
name: str
age: int
def __init__(self, name, age):
self.name = name
self.age = age
self.graduated: bool = False
class Employee:
name: str
age: int
def set_name(self, name) -> "Employee":
self.name = name
return self
è¿é表示 set_name() è¿åäºä¸ä¸ª Employee 对象ã
from typing import Self
class Employee:
name: str
age: int
def set_name(self: Self, name) -> Self:
self.name = name
return self
from typing import TypeVar, Type
T = TypeVar("T")
# "mapper" ç弿¯ä¸ä¸ªå intãstrãMyClass è¿æ ·çç±»å
# "default" æ¯ä¸ä¸ª T ç±»åçå¼ï¼æ¯å¦ 314ã"string"ãMyClass()
# 彿°çè¿åå¼ä¹æ¯ä¸ä¸ª T ç±»åçå¼
def converter(raw, mapper: Type[T], default: T) -> T:
try:
return mapper(raw)
except:
return default
raw: str = input("请è¾å
¥ä¸ä¸ªæ´æ°ï¼")
result: int = converter(raw, mapper=int, default=0)
from typing import TypeVar, Callable, Any
T = TypeVar("T")
def converter(raw, mapper: Callable[[Any], T], default: T) -> T:
try:
return mapper(raw)
except:
return default
# Callable[[Any], T] è¡¨ç¤ºå¼æ¯ä¸ä¸ªåè¿æ ·å£°æç彿°:
# def anynomous(arg: Any) -> T:
# pass
def is_success(value) -> bool:
return value in (0, "OK", True, "success")
resp = dict(code=0, message="OK", data=[])
successed: bool = converter(resp.message, mapper=is_success, default=False)
# è¿æ¯åè¡æ³¨é
""" å¯ä»¥åå¤è¡å符串
使ç¨ä¸ä¸ª"ï¼å¹¶ä¸ç»å¸¸ä½¿ç¨
ä½ä¸ºææ¡£ã
"""
''' å¯ä»¥åå¤è¡å符串
使ç¨ä¸ä¸ª'ï¼å¹¶ä¸ç»å¸¸ä½¿ç¨
ä½ä¸ºææ¡£ã
'''
def double_numbers(iterable):
for i in iterable:
yield i + i
çæå¨å¯å¸®å©æ¨ç¼åæ°æ§ä»£ç
values = (-x for x in [1,2,3,4,5])
gen_to_list = list(values)
# => [-1, -2, -3, -4, -5]
print(gen_to_list)
try:
# 使ç¨âraiseâæ¥å¼åé误
raise IndexError("è¿æ¯ä¸ä¸ªç´¢å¼é误")
except IndexError as e:
pass # passåªæ¯ä¸ä¸ªç©ºæä½ã éå¸¸ä½ ä¼å¨è¿é忢å¤ã
except (TypeError, NameError):
pass # 妿éè¦ï¼å¯ä»¥ä¸èµ·å¤çå¤ä¸ªå¼å¸¸ã
else: # try/except åçå¯éåå¥ã å¿
é¡»éµå¾ªé¤åä¹å¤çææå
容
print("All good!") # ä»
å½ try ä¸çä»£ç æªå¼åå¼å¸¸æ¶è¿è¡
finally: # 卿ææ
åµä¸æ§è¡
print("æä»¬å¯ä»¥å¨è¿éæ¸
çèµæº")
å°ä¸ä¸ªå½æ°åºç¨å°å¯è¿ä»£å¯¹è±¡ï¼å¦å表ï¼çæ¯ä¸ªå ç´ ä¸ï¼å¹¶è¿åä¸ä¸ªæ°çè¿ä»£å¨ã
def square(x):
return x ** 2
ä½¿ç¨ map 彿°
numbers = [1, 2, 3, 4]
result = map(square, numbers)
转æ¢ä¸ºå表æ¥çç»æ
print(list(result)) # è¾åº: [1, 4, 9, 16]
对å¯è¿ä»£å¯¹è±¡è¿è¡æåºï¼è¿åä¸ä¸ªæ°çå·²æåºå表ï¼å对象ä¸åï¼
# æç
§åæ°æåº
users = [
{"name": "Alice", "score": 95, "time": "2023-01-15 10:30:00"},
{"name": "Bob", "score": 88, "time": "2023-01-15 09:45:00"},
{"name": "Charlie", "score": 95, "time": "2023-01-14 15:20:00"},
{"name": "David", "score": 85, "time": "2023-01-16 11:10:00"}
]
# reverse=True代表éåºæåº
sorted_users = sorted(users, key=lambda x: x["score"], reverse=True)
# è¾åºç»æ
for user in sorted_users:
print(f"{user['name']}: {user['score']}")
# ç»æï¼
# Alice: 95
# Charlie: 95
# Bob: 88
# David: 85
å°ä¸ä¸ªäºå 彿°ï¼æ¥åä¸¤ä¸ªåæ°ç彿°ï¼ç´¯ç§¯åºç¨å°å¯è¿ä»£å¯¹è±¡çå ç´ ä¸ï¼æç»å并为å个å¼
from functools import reduce
# å®ä¹ä¸ä¸ªä¹æ³å½æ°
def multiply(x, y):
return x * y
# ä½¿ç¨ reduce 彿°
numbers = [2, 3, 4, 5]
result = reduce(multiply, numbers)
print(result) # è¾åº: 120ï¼2Ã3Ã4Ã5=120ï¼
åºå®å彿°çæäºåæ°ï¼çææ°å½æ°
from functools import partial
# å彿°ï¼è®¡ç® x ç y 次å¹
def power(x, y):
return x ** y
# å建å彿°ï¼åºå® y=2ï¼å³å¹³æ¹å½æ°ï¼
square = partial(power, y=2)
# è°ç¨å彿°
print(square(5)) # è¾åº: 25 (5²)
print(square(10)) # è¾åº: 100 (10²)
pyenv ç¨äºç®¡çpythonçæ¬ï¼pipenv ç¨äºç®¡ç项ç®å çæ¬
# å®è£
pyenv
curl https://pyenv.run | bash
# æ¥ç pyenv å¯ä»¥å®è£
ç python çæ¬å表
pyenv install -l
# æç
§ 3.10 çåç¼æ¾ç¤º python çææ°çæ¬
pyenv latest 3.10
# å®è£
python çæ¬
pyenv install 3.10.14
# æ¥çå·²å®è£
ç python çæ¬
pyenv versions
# 设置 python çæ¬
pyenv global 3.10.14 # å
¨å±è®¾ç½®
pyenv shell 3.10.14 # é对å½å shell session
pyenv local 3.10.14 # é对å½åç®å½
# å®è£
pipenv
pip install pipenv --user # pip
brew install pipenv # homebrew
# æ´æ° pipenv
pip install --user --upgrade pipenv # pip
brew upgrade pipenv # homebrew
# å° pipenv å½ä»¤å å
¥å°ç³»ç»ç¯å¢åé $PATH ä¸ (Unix and MacOS)
dir=$(python -c 'import site; print(site.USER_BASE + "/bin")') # æå° python site-packages bin è·¯å¾
echo 'export PATH="'$dir':$PATH"' >> ~/.zshrc # å° dir è·¯å¾å å
¥å° PATH ä¸
source ~/.zshrc
# å®è£
package
pipenv install <package name> # 䏿å®çæ¬
pipenv install <package name>==<version> # 精确æå®çæ¬
pipenv install <package name>~=<version> # æå®çæ¬èå´ï¼ä¾å¦ 1.1å表示å®è£
1.xçææ°çæ¬ï¼1.0.1å表示å®è£
1.0.xçææ°çæ¬
pipenv install "<package name>=<version>" # 大äºçäºæå®çæ¬
pipenv install "<package name>=<version>" # å°äºçäºæå®çæ¬
# æå® python çæ¬
pipenv --python 3.10.12
# æ¿æ´»å½åç®å½èæç¯å¢
pipenv shell