python笔记
Object-Oriented Programming¶
- Instance attribute are found before class attributes
Accessing Attributes:¶
getattr(tom_account,'balance')
hsaattr(tom_account,'deposit')
有则True,无则False
Inheritance:¶
@property¶
class Link:
empty = ()
def __init__(self,first,rest=empty):
self.first = first
self.rest = rest
@property
def second(self):
return self.rest.first
@second.setter
def second(self,value):
self.rest.first = value
s = Link(3,Link(4,Link(5)))
#如果无@property
s.second()
# 4
#如果有@property
s.second
# 4
s.second = 6
s.second
# 6
Else:¶
Memoization:¶
def memo(f):
cache = {}
def memoized(n):
if n not in cache:
cache[n] = f(n)
return cache[n]
return memoized
Count:¶
def count(f):
def counted(n):
counted.call_count += 1
return f(n)
counter.call_count = 0
return counted
内置函数:¶
iter&next¶
- The order of items in a dictionary is the oreder in which they were added
- for 也实际上用的iter与next
- 在iter一个list时,如果同时改变了list内的元素,可能不能成功遍历list中的所有元素,可以通过copy一个新list来解决。
map&filter:¶
map(func,iterable)
:Only when we ask for the next element is the function applied and the result computedfilter(func,iterable)
: goon until True
enumrate¶
enumrate(sequnce,[strat=0])
# start是下标起始位置
format¶
"{} {}".format("hello","world") # 按默认顺序
# 'hello world'
"{1} {0} {1}".format("hello","world")
# 'world hello world'
zip:¶
- zip()函数将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表
reduce:¶
reduce(f,s,initial)
- f is a two-argument function
- s is a sequence of values that can be the second argument
- 实现reduce的代码:
sum&max&all&any:¶
- sum:
- max:
- all:
all(iterable)
Return True if bool(x) is True for all values x in the iterable.If the iterable is empty,return True. - any:
nay(iterable)
Return True if bool(x) is True for any values x in the iterable.If the itarable is empty,return False.
Assignment Name¶
- python允许:
area,circ = pi*radius**2,2*pi*radius
- 函数定义:
- 赋值顺序: Execution rule for assignment statements:
- Evaluate all expressions to the right of = from left to right
-
Bind all names to the left of = to the resulting values in the current frame
-
Logical Operators * python中任何非0,非空的值均为true
and : - Evaluate the subexpression
- If the result is a false value v,then the expression evaluates to v
- Otherwise,the expression evaluates to the value of the subexpression
So 2 and 3
would evaluate to 3 or - Evaluate the subexpression
- If the result is true valuea v,then the expression evaluates to v
- Otherwise,the expression evaluates to the value of the subexpression
- not
: - x为True,返回False,反之易得
- Evaluate the subexpression
Function¶
Lambda Expressions:¶
- evaluate to functions
Function Currying¶
- Transforming a multi-argument function into a single-argument,higher- order function
Self Reference¶
Function Decorators:¶
def trace(fn):
def wrapped(x):
print("yes")
return fn(x)
return wrapped
@trace
def triple(x):
return x*3
#等价于↓
def triple(x):
return x*3
triple = trace(triple)
- 函数方程:
- *args
Recurison:¶
- Inverse Cascade:
Exception:¶
assert(断言)¶
- assert statements raise an exception of type AssertionError
# assert <expression>,<string>
assert 3 > 2,'is true' # nothing happen
assert 2 > 3,'is false' # 报错,''内为报错显示的信息
# 应用:
def area_square(r):
assert r > 0,'A length much be positive'
return r*r
raise:¶
# raise <expression>
# <expression> must evaluate to subclass of BaseException or an instance of one
raise TypeError('Bad argument')
raise NameError('lalala')
Try Statement:¶
- Try statement handle exceptions
def invert(x):
y = 1/x
print('Never if x is 0')
return y
def invert_safe(x):
try:
return invert(x)
except ZeroDivisionError as e:
print('Handled',e)
return 0
invert_safe(1/0)
# 先operand,报错,所以func还没有来得及called
inverttttttt_safe(1/0)
# 此时报错是NameError,应该是先确认函数存在,再执行operand,最后再执行operator
Container type:¶
List:¶
s[:-1]
从字符串第一个字符开始取,取到倒数第一个字符前为止s[::-1]
相当于reverse- append & extend : append将参数当作一个元素增加到末尾,extend将参数作为一个列表扩展末尾
- slice assignment
- can remove elements from a list by assigning [] to a slice
s = [2,3]
t = [5,6]
s[0:0] = t
# s-> 5,6,2,3
s[3:] = t
# s->5,6,2,5,6
s = [2,3]
t = [5,6]
s[:1] = []
# s -> [3]
t[0:2] = []
# t ->[]
-
pop:remove & return the last element
-
remove:remove the first element equal to the argument
-
addition & slicing create a new lists containing existing elements
a = s + [t]
b = a[1:]
a[1] = 9
#a -> 2,9,[5,6]
b[1][1] = 0
#b -> 3,[5,0]
#t -> [5,0]
#a -> [2,9,[5,0]]
pairs = [[1,2],[2,2],[3,2],[4,4]]
same_count = 0
for x,y in pairs:
if x == y:
same_count += 1
odds = [1,3,5,7,9]
[x+1 for x in odds]
#[2,4,6,8,10]
[x for x in odds if 25 % x == 0]
#[1,5]
# 找约数:
def divisors(n):
return [1] + [x for x in range(2,x) if n%x == 0]
Dictionaries:¶
- 通过关键字确认值
- lists and dictionaries can't be keys
- unordered
Tuples(元组):¶
- 元组和列表类似,不过元组的元素不能修改
- 可以用作字典中的关键字
- An immutable sequence may still change if it contains a mutable value as an element
sets:¶
- Duplicate elements are removed on construction
String¶
- Singe_quoted and double_quoted strings are equivalent
- triple_quoted string can span multiple lines
Generators:¶
- When a generator function is called,it returns a generator that iterate over its yields
yield from
Environment Diagrams:¶
- Every expression is evaluated in the contxt of an environment
- A name evaluates to the value bound to that name in the earliest frame of the current environment in which that name is found
- The parent of a func is the frame in which it was defined
- The parent of a frame is the parent of the function called
Debug¶
UnboundLocalError:¶
https://www.runoob.com/w3cnote/python-unboundlocalerror.html * 在内部函数修改同名全局变量之前调用变量名称,则引发错误 * 内部函数,不修改全局变量,可以访问全局变量 * 内部函数,修改同名全局变量,则python会认为它是一个局部变量