这是test.py:
import sys
a = 50
b = [1,2]
def change():
print "Here 1"
import test
print "Here 2"
test.a = -1
test.b = [0,1]
return
def main():
print "Here 3"
change()
print "Here 4"
print a, b
if 1:
main()
Run Code Online (Sandbox Code Playgroud)
在系统上运行时上面的python代码生成以下输出:
Here 3
Here 1
Here 3
Here 1
Here 2
Here 4
-1 [0, 1]
Here 2
Here 4
50 [1, 2]
Run Code Online (Sandbox Code Playgroud)
令我感到困惑的是为什么没有"Here 1 \n Here 3"输出的无限循环.如何证明打印a,b输出是否合理?
以下代码使python崩溃:
import sys
sys.stdout = sys.stderr = None
print "goodbye world!"
Run Code Online (Sandbox Code Playgroud)
我知道没有真正的理由来编写这样的代码,但我想知道它为什么会崩溃.
我的第一个猜测是print命令失败,因为stdout被覆盖然后,在尝试引发异常时,引发了另一个异常,因为它stderr也被覆盖了.
因此在尝试引发异常时会出现堆栈溢出.
任何人都可以在这里解释背景中真正发生的事情吗?
这是一个堆栈溢出?
有人可以解释这与Python解释器的工作原理背后的逻辑吗?这种行为只是本地线程吗?为什么第二个模块导入后第一个模块导入中的赋值仍然存在?我刚刚进行了长时间的调试会议.
external_library.py
def the_best():
print "The best!"
Run Code Online (Sandbox Code Playgroud)
modify_external_library.py
import external_library
def the_best_2():
print "The best 2!"
external_library.the_best = the_best_2
Run Code Online (Sandbox Code Playgroud)
main.py
import modify_external_library
import external_library
external_library.the_best()
Run Code Online (Sandbox Code Playgroud)
测试:
$ python main.py
The best 2!
Run Code Online (Sandbox Code Playgroud) python monkeypatching side-effects global-variables python-internals
考虑多重分配x[0],y = y,x[0].应用于以下四种情况中的每一种情况,这给出了四种不同的结果.
情况1:
x = [[1,2], [3,4]]
y = [5,6]
Run Code Online (Sandbox Code Playgroud)
给
x = [[5,6], [3,4]]
y = [1,2]
Run Code Online (Sandbox Code Playgroud)案例2:
x = np.array([[1,2], [3,4]])
y = [5,6]
Run Code Online (Sandbox Code Playgroud)
给
x = array([[5,6], [3,4]])
y = array([5,6])
Run Code Online (Sandbox Code Playgroud)案例3:
x = [[1,2], [3,4]]
y = np.array([5,6])
Run Code Online (Sandbox Code Playgroud)
给
x = [array([5,6]), [3,4]]
y = [1,2]
Run Code Online (Sandbox Code Playgroud)案例4:
x = np.array([[1,2], [3,4]])
y = np.array([5,6])
Run Code Online (Sandbox Code Playgroud)
给
x = array([[5,6], [3,4]])
y = array([5,6])
Run Code Online (Sandbox Code Playgroud)看起来列表的多重分配比Numpy阵列的多重分配更智能(自动通过临时变量).
思考?
编辑:事后并不聪明......
我试图与调试的问题abc.ABCMeta-特别是子类的支票,并没有按预期方式工作,我想通过简单地添加一个启动print的__subclasscheck__方法(我知道有调试代码更好的方法,但假装的缘故这个问题别无选择)。但是,在 Python 崩溃之后启动 Python 时(如分段错误),我收到此异常:
Fatal Python error: Py_Initialize: can't initialize sys standard streams
Traceback (most recent call last):
File "C:\...\lib\io.py", line 84, in <module>
File "C:\...\lib\abc.py", line 158, in register
File "C:\...\lib\abc.py", line 196, in __subclasscheck__
RuntimeError: lost sys.stdout
Run Code Online (Sandbox Code Playgroud)
所以把它放在那里显然不是一个好主意print。但异常究竟从何而来?我只更改了 Python 代码,应该不会崩溃吧?
有人知道这个异常来自哪里以及我是否/如何避免它但仍然print在abc.ABCMeta.__subclasscheck__方法中放入一个?
我使用的是 Windows 10、Python-3.5(以防万一它可能很重要)。
在 Python 2.7 中,我可以声明一个新样式的类并使用object.__setattr__以下方法设置一个属性:
class A (object):
def __init__ (self):
object.__setattr__(self, 'foo', 'bar')
A().foo # 'bar'
Run Code Online (Sandbox Code Playgroud)
但是,这在旧式类中不起作用:
class B:
def __init__ (self):
object.__setattr__(self, 'foo', 'bar')
B().foo
Run Code Online (Sandbox Code Playgroud)
类型错误:不能将此 __setattr__ 应用到实例对象
我知道旧式类不支持这种行为,但我不知道为什么它不起作用。
当我调用object.__setattr__旧式类无法实现的新式类时,幕后发生了什么?
请注意,我没有将此代码用于任何目的,我只是想了解它。
每个对象都有一个__dir__属性,如果.__dir__追加额外的引用,命令会停止吗?
>>> dir(''.__dir__)
['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__text_signature__']
Run Code Online (Sandbox Code Playgroud)
和,
>>> dir(''.__dir__.__dir__.__dir__.__dir__)
['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__text_signature__']
Run Code Online (Sandbox Code Playgroud)
它会在足够的时候停止吗?dir '是附加的吗?
我试图在python中反转列表.那里有很多方法,[::-1]看起来很棒!但我很好奇怎么[::-1]办?它的时间复杂度是多少?
我在github中搜索了CPython repo,但我找不到任何线索.我的搜索策略是我搜索了关键词:::CPython repo.由于存在::python语法,即CPython源代码中[::-1]可能存在::,因此[::-1]可以引用它并进行反转.这有意义吗?
请注意,我这个问题仅供参考
我知道标题听起来像是查找内置Python函数的源代码的副本?.但让我解释一下.
比方说,我想找到类most_common方法的源代码collections.Counter.由于Counter该类是在python中实现的,我可以使用该inspect模块获取它的源代码.
即
>>> import inspect
>>> import collections
>>> print(inspect.getsource(collections.Counter.most_common))
Run Code Online (Sandbox Code Playgroud)
这将打印
def most_common(self, n=None):
'''List the n most common elements and their counts from the most
common to the least. If n is None, then list all element counts.
>>> Counter('abcdeabcdabcaba').most_common(3)
[('a', 5), ('b', 4), ('c', 3)]
'''
# Emulate Bag.sortedByCount from Smalltalk
if n is None:
return sorted(self.items(), key=_itemgetter(1), reverse=True)
return _heapq.nlargest(n, self.items(), key=_itemgetter(1))
Run Code Online (Sandbox Code Playgroud)
因此,如果在C中实现的方法或类 …
当查看CPython时tokenizer.c,令牌生成器返回特定的错误消息。
例如,您可以看一下分词器尝试解析十进制数的部分。尝试解析该数字时,5_6一切都应该正常,但是当尝试解析该数字时5__6,令牌生成器应返回SyntaxError并显示消息“无效的十进制文字”:
static int
tok_decimal_tail(struct tok_state *tok)
{
int c;
while (1) {
do {
c = tok_nextc(tok);
} while (isdigit(c));
if (c != '_') {
break;
}
c = tok_nextc(tok);
if (!isdigit(c)) {
tok_backup(tok, c);
syntaxerror(tok, "invalid decimal literal");
return 0;
}
}
return c;
}
Run Code Online (Sandbox Code Playgroud)
使用Python,我尝试达到令牌生成器的SyntaxError消息:
In [12]: try:
...: eval('5__6')
...: except SyntaxError as e:
...: print(e.args, e.filename, e.lineno, e.msg, e.text)
('invalid token', ('<string>', 1, 2, '5__6')) …Run Code Online (Sandbox Code Playgroud) python-internals ×10
python ×9
cpython ×4
python-2.7 ×2
python-3.x ×2
attributes ×1
class ×1
list ×1
numpy ×1
side-effects ×1