You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you just get back a reference to the existing object.
So it should be possible to change the value of 1. I suspect the behavior of Python, in this case, is undefined
some_dict= {}
some_dict[5.5] ="JavaScript"some_dict[5.0] ="Ruby"some_dict[5] ="Python">>some_dict[5.5]
"JavaScript">>>some_dict[5.0] # "Python" destroyed the existence of "Ruby"?"Python">>>some_dict[5]
"Python">>>complex_five=5+0j>>>type(complex_five)
complex>>>some_dict[complex_five]
"Python"
python 中字典的相等性测试是 by equivalence, not identity. 尽管 5,5.0,5 + 0j 都是不同对象,但是都相等
>>>5==5.0==5+0jTrue>>>5isnot5.0isnot5+0jTrue>>>some_dict= {}
>>>some_dict[5.0] ="Ruby">>>5.0insome_dictTrue>>> (5insome_dict) and (5+0jinsome_dict)
True
内心深处,都一样
classWTF:
pass>>>WTF() ==WTF() # two different instances can't be equalFalse>>>WTF() isWTF() # identities are also differentFalse>>>hash(WTF()) ==hash(WTF()) # hashes _should_ be different as wellTrue>>>id(WTF()) ==id(WTF())
True
未完待续
keep trying..
defsome_func():
try:
return'from_try'finally:
return'from_finally'defanother_func():
for_inrange(3):
try:
continuefinally:
print("Finally!")
defone_more_func(): # A gotcha!try:
foriinrange(3):
try:
1/iexceptZeroDivisionError:
# Let's throw it here and handle it outside for loopraiseZeroDivisionError("A trivial divide by zero error")
finally:
print("Iteration", i)
breakexceptZeroDivisionErrorase:
print("Zero division error occurred", e)
>>>some_func()
'from_finally'>>>another_func()
Finally!
Finally!
Finally!
>>>1/0Traceback (mostrecentcalllast):
File"<stdin>", line1, in<module>ZeroDivisionError: divisionbyzero>>>one_more_func()
Iteration0
>>>some_list= [1, 2, 3, 4]
>>>id(some_list)
139798789457608>>>id(some_list[:]) # Notice that python creates new object for sliced list.139798779601192
del remove 和 pop 的区别
del var_name 就是 removes the binding of the var_name from the local or global namespace (That's why the list_1 is unaffected).
remove removes the first matching value, not a specific index, raises ValueError if the value is not found.
pop removes the element at a specific index and returns it, raises IndexError if an invalid index is specified
Why the output is [2, 4]?
迭代开始的时候,删除了 1,然后 list 变成了 2,3,4,这样 2 在 index0,上,下一次删除 index 1 的时候变成删除 3.
Loop variables leaking out!
forxinrange(7):
ifx==6:
print(x, ': for x inside loop')
print(x, ': x in global')
6 : forxinsideloop6 : xinglobal# This time let's initialize x firstx=-1forxinrange(7):
ifx==6:
print(x, ': for x inside loop')
print(x, ': x in global')
# python 2>>>x=1>>>print([xforxinrange(5)])
[0, 1, 2, 3, 4]
>>>print(x)
4# python3>>>x=1>>>print([xforxinrange(5)])
[0, 1, 2, 3, 4]
>>>print(x)
1
In Python, for-loops use the scope they exist in and leave their defined loop-variable behind.
This also applies if we explicitly defined the for-loop variable in the global namespace before.
In this case, it will rebind the existing variable.
Beware of default mutable arguments!
defsome_func(default_arg=[]):
default_arg.append("some_string")
returndefault_arg>>>some_func()
['some_string']
>>>some_func()
['some_string', 'some_string']
>>>some_func([])
['some_string']
>>>some_func()
['some_string', 'some_string', 'some_string']
>>some_func.__defaults__#This will show the default argument values for the function
([],)
>>>some_func()
>>>some_func.__defaults__
(['some_string'],)
>>>some_func()
>>>some_func.__defaults__
(['some_string', 'some_string'],)
>>>some_func([])
>>>some_func.__defaults__
(['some_string', 'some_string'],)
# test for hex functionnum=16print (hex(num)) # 0x10 convert a integer num to hex number;num='1'print(int(num)) # convert a string or float num into int numberprint(float(num))# convert a string or int num into float number# test 2 for global num and id() functionnum=20deffun():
num=100printid(num) #the num object in this function is different from the num outside the function,so the address is differentprintnumfun()
printnum# 20printid(num) #id function return the address of the object# test 3 for global numdefglobal_num():
globalnum# declare using a global numnum=10printnumprintid(num)
num=100global_num()
printid(num) # two address is the sameprintnum# test 4 use of len functionname= ['bruce','Li','Chen']
name1= ('bruce',)
name2= {'bruce':80,'Chen':100}
printlen(name)# return the length of the name listprintlen(name1)
printlen(name)
# test 5 use of locals functiondeflocals_test():
num=1;
num2=2printlocals()
printlen(locals())
locals_test() # return {'num':1,'num2':2} <2></2># test 6 use of list function# the same with tuple functiontmp= ['hello','world',1]
copy_tmp=list(tmp)
printcopy_tmp#['hello', 'world', 1]copy_tmp=list()
printcopy_tmp#[]# test 7 use of raw_input functions=raw_input('--> ') #--> write to the standard outputprints; #if you input 'Hello world',then output 'hello world'# use of open function and try...excepttry:
f=open('a.txt','r') # return a file openjecexceptIOError:
print'can\'t find the file'else:
print'Other errors happen'# test 8 use of dir function return the list of names in the current local scope.classTeacher:
def__init__(self,name,age):
self.name=nameself.age=ageinstance=Teacher('bruce',12)
printdir(instance) #['__doc__', '__init__', '__module__', 'age', 'name']# use of max functionfruit= ['apple','banala','juice']
num= [1,2,3]
printmax(num)
printmax(fruit)
# use of type functionfruit="apple"num=1printtype(fruit) #<type 'str'>printtype(num) #<type 'intdefTryExcept():
try:
...
exceptExceptionase:
printe
## 生成式
{iforiin [1, 2, 2, 3]}
#实际上{1,2,3} 相当于 set([1,2,3])a= {1, 2, 3}
a.remove(4) # 4 不在 set 抛 KeyError 异常a.discard(4) # 不会抛出异常# 添加集合项s= {3, 4, 5}
s.update([1,2,3])
prints# set([1, 2, 3, 4, 5])s<=r# 相当于 s.issubset(r) s 是否为 r 的子集s>=r# 相当于 s.issuperset(r) s 是否为 r 的超集s<r#s 是否为 r 的真子集s>r#s 是否为 r 的真超集s|r# 相当于 s.union(r) 返回 s 和 r 的并集s&t# 相当于 s.intersection(t) 返回 s 和 r 的交集s-t# 相当于 s.difference(t) 返回 s 和 t 的差集(s 有但是 t 没有的元素)s^t# 相当于 s.symmetric_difference(t) 返回个新集合,是 s 或 t 的成员,但不是 s 和 t 共有的成员
## dequed 的的使用使用fromcollectionsimportdeque# ctor which use iterable datad=deque((1, 2, 3))
d1=deque([1, 2, 3])
d2=deque(range(10))
# append data to the end of dequed.append(4) # 1, 2, 3, 4d.appendleft(0) # 0, 1, 2, 3, 4# count the number of deque number which equals 4d.count(4) # 1d.pop() # remove and return the right side of the dequep.popleft() # remove and return the element of left side# extend the right side of the dequed.extend(iterable)
match 表达式
matchvariable:
casevalue1:
# execute code if the value of the variable matches value1casevalue2:
# execute code if the value of the variable matches value2
...
case _:
# execute code if none of the above cases matchdefinterp_exp(e):
# 是 python3.10 的高级特性matche:
caseBinOp(left, Add(), right):
# 获取左右子表达式的值l=interp_exp(left)
r=interp_exp(right)
returnadd64(l, r)
# 减法caseBinOp(left, Sub(), right):
l=interp_exp(left)
r=interp_exp(right)
returnsub64(l, r)
caseUnaryOp(USub(), v):
returnneg64(interp_exp(v))
# 常量值caseConstant(value):
returnvalue# 遇到模式caseCall(Name("input_int"), []):
# 返回输出returninput_int()
case _:
raiseException("error in interp_exp, unexpected "+repr(e))
参考资料
项目组织
tests/test_sub1
$ cd new_project $ python -m unittest discover
is 和 ==
is 用来 check 两个对象是否是同一个,能理解为是同一个地址的对象,是引用的测试
== 是用来比较两个对象的值
当启动 python 时候,会分配 -5 到 256 的对象。
这是因为这些值使用的很频繁
The current implementation keeps an array of integer objects for all integers between -5 and 256, when you create an int in that range you just get back a reference to the existing object.
So it should be possible to change the value of 1. I suspect the behavior of Python, in this case, is undefined
同样的优化适应于不可变的对象,比如空 tuple,而 list 是可变的,所以 is 判断为假。
Both a and b refer to the same object when initialized with same value in the same line.
hash
python 中字典的相等性测试是 by equivalence, not identity. 尽管 5,5.0,5 + 0j 都是不同对象,但是都相等
内心深处,都一样
keep trying..
for
list 坑
能这样避免
output function
list 删除
del remove 和 pop 的区别
Why the output is [2, 4]?
Loop variables leaking out!
Beware of default mutable arguments!
使用 None 来避免
Catching the Exceptions
对于 python2
对于 python3
Wild imports *
common
文件操作
字符串操作
set
字典
如何创建一个字典和给字典赋值
创建一个字典,和给字典赋值都是比较简单的,按照下面,即可创建。
当然,也能使用工厂方法来创建
访问字典中的值
要遍历一个字典,使用
in
操作,然后通过字典键加上括号来访问其值如果访问一个不存在的键将会报错。
如何更新字典
能有几种方式对一个字典做修改:添加一个数据项或者是新元素,修改一个已经存在的数据项,删除一个已经存在的数据项。
如果字典中该键已经存在,则字典中该键对应的值将被新值替代。
删除字典某元素和字典
通常删除整个字典的操作是不常见的,下面记录了删除的代码:
字典方法文档搜索
dict.xxx
。字典方法
构造字典对象
字典构造
字典方法
列表
itertools 操作
collections
match 表达式
打印 requests_oauthlib 库调试日志
#type/python #public
The text was updated successfully, but these errors were encountered: