可否带我飞?
import antigravity
连Python也知道爱是难言的
import this
执行这句会发生什么?
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases ,aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Process finished with exit code 0
这又是一个复活节彩蛋,实际它的源码就一个py文件,打印了这些信息,然后什么都没干
else无处不在
在Python里else已经不局限在if判断里了,它出现在众多逻辑处理中
- for......else......
def does_exists_num(l, to_find):
for num in l:
if num == to_find:
print("Exists!")
break
else:
print("Does not exist")
some_list = [1, 2, 3, 4, 5]
does_exists_num(some_list, 4)
# 输出:Exists!
does_exists_num(some_list, -1)
# 输出:Does not exist
当for循环中执行了break,就不会执行else下的语句,要注意continue不会受此影响
try:
pass
except:
print("Exception occurred!!!")
else:
print("Try block executed successfully...")
# 输出:Try block executed successfully...
同样的不出现异常的时候,执行else语句
私有不私有?
class Yo(object):
def __init__(self):
self.__honey = True
self.bitch = True
Yo().bitch
# 输出:True
Yo().__honey
# AttributeError: 'Yo' object has no attribute '__honey'
Yo()._Yo__honey
# 输出:True
双下划线私有变量如何完成私有变量特性的?实际是python解释器默认把双下划线开头的变量重命名了,命名方式为:_类名__varname
更快的 +=
import timeit
# 用 "+" 连接三个字符串:
print(timeit.timeit("s1 = s1 + s2 + s3", setup="s1 = ' ' * 100000; s2 = ' ' * 100000; s3 = ' ' * 100000", number=100))
# 输出:0.5473556190000001
# 用 "+=" 连接三个字符串:
print(timeit.timeit("s1 += s2 + s3", setup="s1 = ' ' * 100000; s2 = ' ' * 100000; s3 = ' ' * 100000", number=100))
# 输出:0.012764710999999984
连接两个以上的字符串时 += 比 + 更快, 因为在计算过程中第一个字符串 (例如, s1 += s2 + s3 中的 s1) 不会被销毁,就是 += 执行的是追加操作,少了一个销毁新建的动作。
来做个巨大的字符串吧!
def add_string_with_plus(iters):
s = ""
for i in range(iters):
s += "xyz"
assert len(s) == 3*iters
def add_bytes_with_plus(iters):
s = b""
for i in range(iters):
s += b"xyz"
assert len(s) == 3*iters
def add_string_with_format(iters):
fs = "{}"*iters
s = fs.format(*(["xyz"]*iters))
assert len(s) == 3*iters
def add_string_with_join(iters):
l = []
for i in range(iters):
l.append("xyz")
s = "".join(l)
assert len(s) == 3*iters
def convert_list_to_string(l, iters):
s = "".join(l)
assert len(s) == 3*iters
print(timeit(add_string_with_plus(10000)))
# 输出:1000 loops, best of 3: 972 μs per loop
print(timeit(add_bytes_with_plus(10000)))
# 输出:1000 loops, best of 3: 815 μs per loop
print(timeit(add_string_with_format(10000)))
# 输出:1000 loops, best of 3: 508 μs per loop
print(timeit(add_string_with_join(10000)))
# 输出:1000 loops, best of 3: 878 μs per loop
l = ["xyz"] * 10000
print(timeit(convert_list_to_string(l, 10000)))
# 输出:10000 loops, best of 3: 80 μs per loop
# 我们将迭代次数增加10倍.
print(timeit(add_string_with_plus(100000))) # 执行时间线性增加
# 输出: 100 loops, best of 3: 9.75 ms per loop
print(timeit(add_bytes_with_plus(100000))) # 二次增加
# 输出:1000 loops, best of 3: 974 ms per loop
print(timeit(add_string_with_format(100000))) # 线性增加
# 输出:100 loops, best of 3: 5.25 ms per loop
print(timeit(add_string_with_join(100000))) # 线性增加
# 输出:100 loops, best of 3: 9.85 ms per loop
l = ["xyz"]*100000
print(timeit(convert_list_to_string(l, 100000))) # 线性增加
# 输出:1000 loops, best of 3: 723 μs per loop
def add_string_with_plus(iters):
s = ""
for i in range(iters):
s = s + "x" + "y" + "z"
assert len(s) == 3*iters
print(timeit(add_string_with_plus(10000)))
# 输出:100 loops, best of 3: 9.87 ms per loop
print(timeit(add_string_with_plus(100000))) # 执行时间二次增加
# 输出:1 loops, best of 3: 1.09 s per loop
[] = ()
看着奇怪但能正确运行的语句,语句在语义上是正确的 (解包一个空的 tuple 并赋值给 list)'a'[0][0][0][0][0] 在语义上也是正确的, 因为在 Python 中字符串同时也是序列(可迭代对象支持使用整数索引访问元素).
++和--运算符
a = 5
print(a)
# 输出:5
print(++a)
# 输出:5
print(--a)
# 输出:5
注意python 里没有 ++ 操作符. 这其实是两个 + 操作符.++a 被解析为 +(+a) 最后等于 a. --a 同理.
本地变量数量
Python 使用 2个字节存储函数中的本地变量.
理论上, 这意味着函数中只能定义65536个变量. 但是,Python 内置了一个方便的解决方案,可用于存储超过2^16个变量名. 下面的代码演示了当定义了超过65536个局部变量时堆栈中发生的情况
import dis
exec("""
def f():
""" + """
""".join(["X"+str(x)+"=" + str(x) for x in range(65539)]))
f()
print(dis.dis(f))
'abc'.count('') == 4
print('abc'.count('') == 4)
# 输出:True
下面这个方法能更好的说明问题
def count(s, sub):
result = 0
for i in range(len(s) + 1 - len(sub)):
result += (s[i:i + len(sub)] == sub)
return result
这个行为是由于空子串('')与原始字符串中长度为0的切片相匹配导致的.