根据本指南python描述符 https://docs.python.org/2/howto/descriptor.html
新样式类中的方法对象是使用描述符实现的,以避免在属性查找中特殊包装它们.
我理解这一点的方法是有一个方法对象类型实现__get__并在使用实例和未绑定的方法对象调用时返回绑定的方法对象,在没有实例和只有类的情况下调用.文章还指出,这个逻辑是在object .__ getattribute__方法中实现的.像这样:
def __getattribute__(self, key):
"Emulate type_getattro() in Objects/typeobject.c"
v = object.__getattribute__(self, key)
if hasattr(v, '__get__'):
return v.__get__(None, self)
return v
Run Code Online (Sandbox Code Playgroud)
但是对象.__ getattribute__本身就是一种方法!那怎么绑定一个对象(没有无限递归)?如果它在属性查找中是特殊的,那不会破坏删除旧式特殊套管的目的吗?
对于以下代码:
import sys
x=(i for i in range(1,11))
print x
print 'Before starting iterating generator size is' ,sys.getsizeof(x)
print 'For first time'
for i in x:
print i
print 'For second time , does not print anything'
for i in x:
print i # does not print anything
print 'After iterating generator size is' ,sys.getsizeof(x)
Run Code Online (Sandbox Code Playgroud)
输出是:
<generator object <genexpr> at 0x014C1A80>
Before starting iterating generator size is 40
For first time
1
2
3
4
5
6
7
8
9 …Run Code Online (Sandbox Code Playgroud) 我尝试了下一个代码:
>>> f = object()
# It's obvious behavior:
>>> f.foo
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'foo'
# However, the next one is surprising me!
>>> getattr(f, 'foo')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'object' object has no attribute 'foo'
# And this one returns None as expected:
>>> getattr(f, 'foo', None)
Run Code Online (Sandbox Code Playgroud)
然后我getattr()在PyCharm IDE中找到了这个伪签名:
def getattr(object, name, default=None): # known …Run Code Online (Sandbox Code Playgroud) 你能解释一下链式比较的句法分析树是什么样的吗?
据我所知,在大多数语言中,它基于运算符关联性构造节点,a < b < c因此将有一个布尔值作为左手或右手操作数.
但是在Python中,这样的表达式几乎等同于a < b and b < c(b仅评估一次).
这种转变的生成语法规则是什么?基本上,Python解释器在这种情况下构造解析树的作用是什么?
我正在使用Anaconda(Python 3.6).
在交互模式下,我对正整数> 256进行了对象标识测试:
# Interactive test 1
>>> x = 1000
>>> y = 1000
>>> x is y
False
Run Code Online (Sandbox Code Playgroud)
显然,在单独的行中写入的大整数(> 256)不会在交互模式下重复使用.
但是如果我们在一行中编写赋值,则重用大的正整数对象:
# Interactive test 2
>>> x, y = 1000, 1000
>>> x is y
True
Run Code Online (Sandbox Code Playgroud)
也就是说,在交互模式下,在一行或单独的行中写入整数赋值会对重用整数对象(> 256)产生影响.对于[-5,256]中的整数(如https://docs.python.org/2/c-api/int.html所述),缓存机制确保只创建一个对象,无论赋值是否相同或不同的线条.
现在让我们考虑小于-5的小负整数(任何超出范围[-5,256]的负整数都可以达到目的),出现了令人惊讶的结果:
# Interactive test 3
>>> x, y = -6, -6
>>> x is y
False # inconsistent with the large positive integer 1000
>>> -6 is -6
False
>>> id(-6), id(-6), id(-6)
(2280334806256, 2280334806128, 2280334806448)
>>> …Run Code Online (Sandbox Code Playgroud) 我正在使用symtable一段代码的符号表.奇怪的是,当使用理解(listcomp,setcomp等)时,我还没有定义一些额外的符号.
复制(使用CPython 3.6):
import symtable
root = symtable.symtable('[x for x in y]', '?', 'exec')
# Print symtable of the listcomp
print(root.get_children()[0].get_symbols())
Run Code Online (Sandbox Code Playgroud)
输出:
[<symbol '.0'>, <symbol '_[1]'>, <symbol 'x'>]
Run Code Online (Sandbox Code Playgroud)
符号x是预期的.但是什么.0和_[1]?
请注意,对于任何其他非理解构造,我正好得到了我在代码中使用的标识符.例如,lambda x: y仅产生符号[<symbol 'x'>, <symbol 'y'>].
此外,文档说这symtable.Symbol是......
SymbolTable与源中的标识符对应的条目.
......虽然这些标识符显然没有出现在源代码中.
Python的集合与NaNs(现在直播)的行为令人费解(至少对我而言):
>>> float('nan') in {float('nan')} # example 1
False
>>> nan = float('nan') # example 2
>>> nan in {nan}
True
Run Code Online (Sandbox Code Playgroud)
起初,我错误地认为,这是==-operator 的行为,但显然不是这种情况,因为两种情况都False按预期产生(这里是实时的):
>>> float('nan') == float('nan')
False
>>> nan = float('nan')
>>> nan == nan
False
Run Code Online (Sandbox Code Playgroud)
我主要对这种行为的原因感兴趣.但是如果有办法确保一致的行为,那也很高兴知道!
x=300
y=300
print(id(x),id(y))
a=[300,300]
print(id(a[0]),id(a[1]))
Run Code Online (Sandbox Code Playgroud)
在上面的代码执行我得到不同的地址x和y,但相同的地址a[0]和a[1].谁能告诉我为什么会这样?
Cpython优化字符串增量操作,在为字符串初始化内存时,程序为其留下额外的扩展空间,因此,在递增时,原始字符串不会复制到新位置.我的问题是为什么字符串变量的id会发生变化.
>>> s = 'ab'
>>> id(s)
991736112104
>>> s += 'cd'
>>> id(s)
991736774080
Run Code Online (Sandbox Code Playgroud)
为什么string变量的id改变了.
考虑下面这段代码:
import timeit
import dis
class Bob(object):
__slots__ = "_a",
def __init__(self):
self._a = "a"
@property
def a_prop(self):
return self._a
bob = Bob()
def return_attribute():
return bob._a
def return_property():
return bob.a_prop
print(dis.dis(return_attribute))
print(dis.dis(return_property))
print("attribute:")
print(timeit.timeit("return_attribute()",
setup="from __main__ import return_attribute", number=1000000))
print("@property:")
print(timeit.timeit("return_property()",
setup="from __main__ import return_property", number=1000000))
Run Code Online (Sandbox Code Playgroud)
很容易看到return_attribute并return_property导致相同的字节码:
17 0 LOAD_GLOBAL 0 (bob)
3 LOAD_ATTR 1 (_a)
6 RETURN_VALUE
None
20 0 LOAD_GLOBAL 0 (bob)
3 LOAD_ATTR 1 (a_prop)
6 RETURN_VALUE
None
Run Code Online (Sandbox Code Playgroud)
但是,时间有所不同:
17 0 LOAD_GLOBAL …Run Code Online (Sandbox Code Playgroud) python ×10
python-internals ×10
python-3.x ×4
cpython ×3
attributes ×1
built-in ×1
generator ×1
integer ×1
parsing ×1
performance ×1
properties ×1