我试图list使用该inspect模块检索该类的源代码,但没有成功:
>>> import inspect
>>> inspect.getsource(list)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/inspect.py", line 701, in getsource
lines, lnum = getsourcelines(object)
File "/usr/lib/python2.7/inspect.py", line 690, in getsourcelines
lines, lnum = findsource(object)
File "/usr/lib/python2.7/inspect.py", line 526, in findsource
file = getfile(object)
File "/usr/lib/python2.7/inspect.py", line 408, in getfile
raise TypeError('{!r} is a built-in class'.format(object))
TypeError: <module '__builtin__' (built-in)> is a built-in class
Run Code Online (Sandbox Code Playgroud)
我不明白为什么这不工作- 该文档inspect.getsource()称,
如果无法检索源代码,则会引发IOError.
......但不解释为什么会发生这种情况(无论如何我得到了一个TypeError,而不是一个IOError). …
我们在Python中称之为"堆栈"是什么?它是CPython的C堆栈吗?我读到Python堆栈帧是在堆中分配的.但我认为堆栈的目标是...堆栈堆栈帧.那堆栈到底是做什么的?
我可以从具有相同名称的函数调用全局函数吗?
例如:
def sorted(services):
return {sorted}(services, key=lambda s: s.sortkey())
Run Code Online (Sandbox Code Playgroud)
通过{sorted}我的意思是,全球排序功能.有没有办法做到这一点?然后我想用模块名称调用我的函数: service.sorted(services)
我想使用相同的名称,因为它与全局函数的作用相同,只是它添加了一个默认参数.
在python中,您无法直接比较lambda表达式创建的函数:
>>> (lambda x: x+2) == (lambda x: x+2)
False
Run Code Online (Sandbox Code Playgroud)
我做了一个例程来散列反汇编.
import sys
import dis
import hashlib
import contextlib
def get_lambda_hash(l, hasher=lambda x: hashlib.sha256(x).hexdigest()):
@contextlib.contextmanager
def capture():
from cStringIO import StringIO
oldout, olderr = sys.stdout, sys.stderr
try:
out=[StringIO(), StringIO()]
sys.stdout, sys.stderr = out
yield out
finally:
sys.stdout, sys.stderr = oldout, olderr
out[0] = out[0].getvalue()
out[1] = out[1].getvalue()
with capture() as out:
dis.dis(l)
return hasher(out[0])
Run Code Online (Sandbox Code Playgroud)
用法是:
>>>> get_lambda_hash(lambda x: x+2) == get_lambda_hash(lambda x: x+1)
False
>>>> get_lambda_hash(lambda x: x+2) == get_lambda_hash(lambda …Run Code Online (Sandbox Code Playgroud) 我有一个python程序,它从文件中读取行并将它们放入dict中,简单来说,它看起来像:
data = {'file_name':''}
with open('file_name') as in_fd:
for line in in_fd:
data['file_name'] += line
Run Code Online (Sandbox Code Playgroud)
我发现它需要几个小时才能完成.
然后,我对程序做了一些改动:
data = {'file_name':[]}
with open('file_name') as in_fd:
for line in in_fd:
data['file_name'].append(line)
data['file_name'] = ''.join(data['file_name'])
Run Code Online (Sandbox Code Playgroud)
它在几秒钟内完成.
我认为这+=会使程序变慢,但似乎没有.请查看以下测试的结果.
我知道我们可以使用list append和join来提高concat字符串的性能.但我从未想过追加和加入以及添加和分配之间存在这样的性能差距.
所以我决定做更多的测试,最后发现它是dict更新操作使程序疯狂地慢.这是一个脚本:
import time
LOOPS = 10000
WORD = 'ABC'*100
s1=time.time()
buf1 = []
for i in xrange(LOOPS):
buf1.append(WORD)
ss = ''.join(buf1)
s2=time.time()
buf2 = ''
for i in xrange(LOOPS):
buf2 += WORD
s3=time.time()
buf3 = {'1':''} …Run Code Online (Sandbox Code Playgroud) 我正在咨询Python 3.6的官方Python语法规范.
我无法找到任何注释语法(它们显示在a前面#)和文档字符串(它们应该出现''').快速查看词法分析页面也没有帮助 - 文档字符串在那里被定义,longstrings但没有出现在语法规范中.名称的类型会STRING进一步显示,但不会引用其定义.
鉴于此,我很好奇CPython编译器如何知道注释和文档字符串是什么.这项壮举是如何完成的?
我最初猜测,CPython编译器在第一次传递中删除了注释和文档字符串,但随后又乞求了如何help()呈现相关文档字符串的问题.
为什么next我动态绑定到类的实例的这个方法失败并返回一个非迭代器对象?
from collections import Iterator
from collections import Iterable
from types import MethodType
def next(cls):
if cls.start < cls.stop:
cls.start += 1
return cls.start
else:
raise StopIteration
class Foo(object):
start, stop = 0, 5
def __iter__(self):
return self
if __name__ == "__main__":
foo = Foo()
setattr(foo, 'next', MethodType(next, foo, Foo))
print hasattr(foo, "next")
if isinstance(foo, Iterable):
print "iterable"
if isinstance(foo, Iterator):
print "iterator"
for i in foo:
print i
Run Code Online (Sandbox Code Playgroud)
输出:
iterable
True
TypeError: iter() returned non-iterator of type …Run Code Online (Sandbox Code Playgroud) 函数调用总会产生一些开销.但为什么下面的代码显示非函数调用较慢.
import time
def s():
for i in range(1000000000):
1 + 1
t = time.time()
s()
print("Function call: " + str(time.time() - t))
t = time.time()
for i in range(1000000000):
1 + 1
print("Non function call: " + str(time.time() - t))
Run Code Online (Sandbox Code Playgroud)
Function call: 38.39736223220825
Non function call: 60.33238506317139
Run Code Online (Sandbox Code Playgroud) 根据Python的文档,reversed()使用__getitem__和__len__if __reversed__未实现.
我遇到了一个奇怪的行为,但未能解释它:
>>> class A(dict):
... pass
...
>>> reversed(A())
Traceback (most recent call last):
...
TypeError: 'A' object is not reversible
>>> class B(dict):
... def __getitem__(self, key):
... return super().__getitem__(key)
... def __len__(self):
... return super().__len__()
...
>>> reversed(B())
Traceback (most recent call last):
...
TypeError: 'B' object is not reversible
>>> class C:
... def __getitem__(self, key):
... return "item"
... def __len__(self):
... return 1
... …Run Code Online (Sandbox Code Playgroud) 一个tuple在python(在码块)由逗号定义; 括号不是必需的(在以下情况下)。所以这三个都是等效的:
a, b = 1, 2
a, b = (1, 2)
(a, b) = 1, 2
Run Code Online (Sandbox Code Playgroud)
如果我定义一个功能
def f(a, b):
print(a, b)
Run Code Online (Sandbox Code Playgroud)
以这种方式调用它将起作用:
f(2, 3)
Run Code Online (Sandbox Code Playgroud)
这不会:
f((2, 3))
# TypeError: f() missing 1 required positional argument: 'b'
Run Code Online (Sandbox Code Playgroud)
当它们是函数参数时,python如何区别元组?这里的括号是必须的(我明白为什么会这样,我很高兴python可以这样工作!)。
我的问题是:当它们是函数参数时,python如何区别元组。
python ×10
python-internals ×10
cpython ×3
python-3.x ×3
function ×2
dictionary ×1
grammar ×1
iterator ×1
lambda ×1
list ×1
namespaces ×1
performance ×1
python-2.7 ×1
python-2.x ×1
tuples ×1