我正在尝试创建一个具有通用类型的数据类,我可以将其解压并作为 numpy 的 linspace 的参数提供。__iter__为此,我需要使用 TypeVar给出返回类型:
from typing import Iterator, Union, Generic, TypeVar, Any
import numpy as np
VT = TypeVar("VT", bound=float)
class Arguments(Generic[VT]):
def __init__(self, start: VT, stop: VT, num: int):
self.start = start
self.stop = stop
self.num = num
def __iter__(self) -> Iterator[Union[VT, int]]:
return iter([self.start, self.stop, self.num])
args: Arguments[float] = Arguments(1.2, 2.5, 10)
print(np.linspace(*args))
Run Code Online (Sandbox Code Playgroud)
执行工作正常,但 mypy (0.920) 失败并出现以下错误:
$ mypy test.py
test.py:17: error: No overload variant of "linspace" matches argument type "Arguments[float]" [call-overload]
test.py:17: note: …Run Code Online (Sandbox Code Playgroud) 我想在Python中调用一个函数,允许我在执行期间访问所有当前变量(用于调试).像这样的东西:
def interruptWithTerminal():
interruptchoice = ""
while interruptchoice != "Y":
interruptchoice = raw_input("print what variable? (Y to continue script): ")
try:
print eval(interruptchoice)
except:
print "Error"
Run Code Online (Sandbox Code Playgroud)
我的问题是我在调用此函数时无法访问变量.有任何想法吗?
我想将一个函数应用于a的每个元素numpy.ndarray,如下所示:
import numpy
import math
a = numpy.arange(10).reshape(2,5)
b = map(math.sin, a)
print b
Run Code Online (Sandbox Code Playgroud)
但这给了:
TypeError: only length-1 arrays can be converted to Python scalars
Run Code Online (Sandbox Code Playgroud)
我知道我可以这样做:
import numpy
import math
a = numpy.arange(10).reshape(2,5)
def recursive_map(function, value):
if isinstance(value, (list, numpy.ndarray)):
out = numpy.array(map(lambda x: recursive_map(function, x), value))
else:
out = function(value)
return out
c = recursive_map(math.sin, a)
print c
Run Code Online (Sandbox Code Playgroud)
我的问题是:是否有内置函数或方法来执行此操作?它似乎很简单,但我找不到它.我在用Python 2.7.