我正在查看有关前向引用的 PEP 484 部分并注意到以下声明:
...该定义可以表示为字符串文字,稍后再解析。
这让我想知道,“稍后”是什么时候,什么时候?解释器稍后不会尝试将其解析为文字,那又如何呢?是否只是编写了第三方工具来做到这一点?
演示解释器结果的小例子:
class A:
def test(self, a: 'A') -> None:
pass
class B:
def test(self, a: A) -> None:
pass
>>> A().test.__annotations__
{'a': 'A', 'return': None}
>>> B().test.__annotations__
{'a': <class '__main__.A'>, 'return': None}
Run Code Online (Sandbox Code Playgroud)
如果我对函数注释和类型提示的理解是正确的,那么 Python在运行时并没有真正对它们做任何事情来提高性能,而是内省的使用允许严格的第三方应用程序,例如 linter、IDE 和静态分析工具(例如mypy)以利用它们的可用性。那么这些工具是否会尝试解决类型提示'A'而不是将其作为解释器的工作,如果是这样,他们如何实现这一点?
更新:
通过使用该typing模块,用户代码可以执行以下操作:
>>> typing.get_type_hints(A().test)
{'a': <class '__main__.A'>, 'return': <class 'NoneType'>}
>>> typing.get_type_hints(B().test)
{'a': <class '__main__.A'>, 'return': <class 'NoneType'>}
Run Code Online (Sandbox Code Playgroud)
但是,我的问题是针对 Python 是否有责任__annotations__从字符串文字更新函数的 ,也就是说在运行时更改:
>>> A().test.__annotations__ …Run Code Online (Sandbox Code Playgroud) 我已经通过将导入移到顶部声明来解决我的问题,但它让我想知道:为什么我不能使用'__main__'在作为目标的函数中导入的模块multiprocessing?
例如:
import os
import multiprocessing as mp
def run(in_file, out_dir, out_q):
arcpy.RaterToPolygon_conversion(in_file, out_dir, "NO_SIMPIFY", "Value")
status = str("Done with "+os.path.basename(in_file))
out_q.put(status, block=False)
if __name__ == '__main__':
raw_input("Program may hang, press Enter to import ArcPy...")
import arcpy
q = mp.Queue()
_file = path/to/file
_dir = path/to/dir
# There are actually lots of files in a loop to build
# processes but I just do one for context here
p = mp.Process(target=run, args=(_file, _dir, q))
p.start()
# …Run Code Online (Sandbox Code Playgroud) 我正在编写一本关于运算符重载的示例教科书,它让我想知道返回"常量值"(例如operator+).据我了解,如果我作为a返回任何内容const,则以后无法修改.说我有这个粗略的例子:
#include <iostream>
using namespace std;
class Temp {
private:
int val;
public:
Temp(){};
Temp(int v):val(v){};
const Temp operator+(const Temp& rhs) const {
return Temp(this->val + rhs.val);
}
int getVal() { return this->val; }
void setVal(int v) { this->val = v; }
};
int main() {
Temp t1, t2, t3;
t1 = Temp(4);
t2 = Temp(5);
t3 = t1 + t2;
cout << t3.getVal() << endl;
t3.setVal(100);
cout << t3.getVal() << endl;
}
Run Code Online (Sandbox Code Playgroud)
之后t3 = …
如果x和y是double,为什么我不能这样做:
int nx = floor(x)或者int ny = floor(y)向下舍入到可以使用的整数int?
如何在for循环中递增,以便:
for (int j = 0; j < 1.0; j+=0.01) {}
我立刻就知道有一个小数点可以使用int奇数.
编辑:
在任何人变得厚颜无耻之前,我已经知道int是不正确的...问题是如何执行该方法,因为int这不是一种有效的方式.