有趣的python
r = [x*x for x in range(1, 11)] print(r)# 輸出:[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
在Haskell中稱為ofollow,noindex">List comprehension 的,寫法與其類似:[x*x | x <- [1..10]]
型別是小寫的
# str即是表示字串型別 def myFunc(s: str): # some code
引數型別是可選的,一般不需要加
與、或操作符,是用and、or來表示的
b1 = True b2 = False o1 = b1 and b2# False o2 = b1 or b2# True
可以執行字串
exec("print('Hello World')")# 輸出:Hello World
類似js中的eval
列表可以從後面來訪問
lst = [1, 2, 3] print(lst[-1])# 輸出3, 也要注意不能越界
支援lambda表示式
lambda r, v : r + v
簡單的交換變數的方式
x, y = y, x
類似swift的寫法,本質都是利用元組來交換:(x, y) = (y, x)
for-else結構
lst = [1, 3, 5, 7, 9, 13, 19] for i in lst: if i % 2 == 0: print("找到了偶數") break else: print("沒有找到偶數")# 輸出:沒有找到偶數
成員變數要在__init__裡面指定,在方法外定義的是類屬性
class Student(object): count = 0 def __init__(self, name, score): self.name = name self.score = score Student.count += 1 m = Student("MMMM", 80) print(Student.count)# 1 print(m.name)# MMMM
私有變數通過名字來限定
通過在名字前加雙下劃線,來表示是私有變數。
class Student(object): def __init__(self, name, score): self.__name = name self.__score = score s = Student("Matthew", 60) print(s.__name)# 'Student' object has no attribute '__name'
類可以動態的增、刪成員變數
class Student(object): pass o = Student() o.name = "Matthew" print(o.name)# 輸出: Matthew del o.name print(o.name)# 'Student' object has no attribute 'name'
js也有這個能力
呼叫不存在的屬性,可以被開發者接管
class Student(object): def __getattr__(self, attr): if attr == 'name': return "Good" o = Student() print(o.name)# 輸出:Good
跟OC的轉發找不到的方法非常像。包括__str__
方法,也非常類似OC中的description
,來實現自定義列印內容
可以通過程式碼來設定斷點
pdb.set_trace()
有點類似js的debugger
語句