我想知道__init__和__call__方法之间的区别.
例如:
class test:
def __init__(self):
self.a = 10
def __call__(self):
b = 20
Run Code Online (Sandbox Code Playgroud) 基本上,我想要实现的是编译时验证(可能很好的错误消息)注册可调用(函数,lambda,带调用运算符的结构)具有正确的签名.示例(static_assert要填写的内容):
struct A {
using Signature = void(int, double);
template <typename Callable>
void Register(Callable &&callable) {
static_assert(/* ... */);
callback = callable;
}
std::function<Signature> callback;
};
Run Code Online (Sandbox Code Playgroud) c++ templates template-meta-programming c++11 callable-object
问题标题的措辞可能不正确,我会很乐意根据您的建议进行修复。
我的问题可以用这个片段来说明:
#include <array>
template <typename Callable>
constexpr auto make_array_ok(Callable callable) {
return std::array<int, callable()>{};
};
// constexpr auto make_array_bad(std::size_t s)
// {
// return std::array<int,s>{};
// };
int main(int argc, char**) {
static_cast<void>(argc);
auto size = []() { return std::size_t{42}; };
// fails to compile -- as I expected
// auto size_dyn = [argc]() { return std::size_t(argc); };
// auto a = make_array_ok(size_dyn);
// also fails to compile -- but why?
// auto size_capt = [arg = size()]()constexpr{return arg;}; …Run Code Online (Sandbox Code Playgroud) 我有一个数字列表.
我试图过滤列表,只保留正数.
我试图通过传递lambda作为参数来做到这一点.
我想知道为什么我会出现函数不匹配错误.
#include <vector>
#include <algorithm>
#include <functional>
template<typename T>
std::vector<T> keep(
const std::vector<T> &original,
std::function<bool(const T&)> useful)
{
std::vector<T> out;
for(T item:original)
{
if(useful(item))
out.push_back(item);
}
return out;
}
int main()
{
std::vector<int> a={4,6,2,-5,3,-8,13,-11,27};
a=keep(a,[](const int& x)->bool{return x>0;});
for(int y:a)
{
std::cout<<y<<std::endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这是错误消息:
error: no matching function for call to ‘keep(std::vector<int>&, main()::<lambda(const int&)>)’
a=keep(a,[](const int& x)->bool{return x>0;});
^
Run Code Online (Sandbox Code Playgroud) 当传递函数时,我通常用 来提示它们typing.Callable。
的文档声明collections.abc.Callable它有四种 dunder 方法:
类 collections.abc.Callable
分别提供方法
__contains__()、__hash__()、__len__()和的类的 ABC__call__()。
有一次,我想检查__wrapped__函数上是否有属性。通过检查,这在运行时工作得很好hasattr(func, "__wrapped__")。
当使用 进行静态类型检查时mypy,它会报告:error: "Callable[..., Any]" has no attribute "__wrapped__" [attr-defined]。这对我来说很有意义,因为Callable不应该有__wrapped__属性。
如何正确输入Callable带有__wrapped__属性的提示 a?我可以做一些其他类型的提示或解决方法吗?
代码示例
我正在使用mypy==0.782和Python==3.8.2:
from functools import wraps
from typing import Callable
def print_int_arg(arg: int) -> None:
"""Print the integer argument."""
print(arg)
@wraps(print_int_arg)
def wrap_print_int_arg(arg: int) -> None: …Run Code Online (Sandbox Code Playgroud) 我有兴趣获得一种获取可调用 Python 对象所采用的参数和关键字参数列表的通用方法。对于具有 function 的函数来说,这很简单inspect.getargspec,例如:
import inspect
from functools import partial
def foo(*args, **kwargs):
return args, kwargs
print(inspect.getargspec(foo))
>>ArgSpec(args=[], varargs='args', keywords='kwargs', defaults=None)
def bar(*args):
return args
print(inspect.getargspec(bar))
>>ArgSpec(args=[], varargs='args', keywords=None, defaults=None)
Run Code Online (Sandbox Code Playgroud)
但是,在以下情况下此操作会失败:
partial_function = partial(foo, kwarg="value")
inspect.getargspec(partial_function)
>>TypeError: <functools.partial object at 0x11748bc58> is not a Python function
class Foo(object):
def __call__(self, *args, **kwargs):
return args, kwargs
foo_instance = Foo()
inspect.getargspec(foo_instance)
>>TypeError: <__main__.Foo object at 0x116c13ed0> is not a Python function
inspect.getargspec(zip)
>>TypeError: <built-in function zip> is not a …Run Code Online (Sandbox Code Playgroud) 我研究了这个主题,但找不到明确的解决方案。有一个类似的SO问题
我的问题是我有一个带有注释的类attr.dataclass,typing_extensions.final我不希望记录它们,但我仍然想从如何调用该类的角度来描述该类。
例如,
@final
@dataclass(frozen=True, slots=True)
class Casting(object):
_int_converter_function = int
_float_converter_function = float
def __call__(self, casting, value_to_cast):
if casting['type'] == 'integer':
return self._int_converter_function(value_to_cast)
return self._float_converter_function(value_to_cast)
Run Code Online (Sandbox Code Playgroud)
这大约相当于这个(远不准确):
class Casting(object):
def __init__(
self,
int_converter_function = int,
float_converter_function = float,
):
self.int_converter_function = int_converter_function
self.float_converter_function = float_converter_function
def converter(self, casting, value):
self.value = value
yield
type = casting['type']
if type == 'integer':
yield self.int_converter_function(value)
else:
yield self.float_converter_function(value)
Run Code Online (Sandbox Code Playgroud)
最新的情况很明显,我可以使用文档字符串和Sphinxdo 来记录每个方法:
.. autoclass:: package.Casting
:members:
.. automethod:: …Run Code Online (Sandbox Code Playgroud) 你能告诉我为什么这段代码有效吗?replace_if算法使用重载的operator().在main函数中,我创建了IsEqual类的常量对象,因此只应使用常量函数成员.某种程度上,constancy不起作用,并且该运算符被调用.
#include <iostream>
#include <vector>
#include <algorithm>
class IsEqual {
int value;
public:
IsEqual(int v) : value(v) {}
bool operator()(const int &elem){
this->value=6;
return elem == value;
}
};
int main()
{
const IsEqual tst(2);
std::vector<int> vec = {3,2,1,4,3,7,8,6};
std::replace_if(vec.begin(), vec.end(), tst, 5);
for (int i : vec) std::cout << i << " ";
std::cout<<std::endl;
}
Run Code Online (Sandbox Code Playgroud)
结果:3 2 1 4 3 7 8 5
在Julia中,确定对象是否可调用的最佳方法是什么?(例如,是否存在python callable函数的模拟?)
编辑:这是人们所希望的:
f() = println("Hi")
x = [1,2,3]
a = 'A'
callable(f) # => true
callable(x) # => false
callable(a) # => false
callable(sin) # => true
Run Code Online (Sandbox Code Playgroud) 在python 3.1问世时,我有一些旧的程序.在程序中我经常使用它Callable()传递一个函数,它的参数就像我的TKinter应用程序:
tvf.mi(datei_bu, text=datei_opt, command=Callable(exec_datei_opts, datei_opt))
Run Code Online (Sandbox Code Playgroud)
现在我想再次使用我的程序,但是callable- 对象已经消失了.在网络上,我发现在python 3.2中删除了这个功能,没有一个替代方案适合我.
最后我决定重新安装python 3.1.但是,我不知道是否可以同时安装多个python 3版本,或者当我想使用这个特殊版本时如何为这个版本"创建"一个shell命令.
我的问题是:
Callable- 被删除的对象?callable-object ×10
python ×5
c++ ×4
c++11 ×2
class ×1
constants ×1
julia ×1
lambda ×1
mypy ×1
object ×1
oop ×1
python-3.1 ×1
templates ×1
this ×1
type-hinting ×1