我有方法,在这个方法中可能会发生致命错误,因为我抓住了这个错误
class a {
function shutDownFunction() {
$error = error_get_last();
if ($error['type'] == 1) {
echo "this is fatal error";
}
}
function terribleFunction () {
register_shutdown_function(array($this,'shutdownFunction'));
// here is code, wich may causes fatal error
}
}
Run Code Online (Sandbox Code Playgroud)
好了,这个理解,但我需要通过参数terribleFunction来shutDownFunction.怎么做到这个?
我想在一个单独的线程中执行不同的方法,具体取决于给构造函数的参数.但是,Callable接口只允许一种返回参数.
它应该像这样工作:
Future<String> result =
executor.submit(ClassThatImplementsCallable(RETURN_STRING));
Future<Integer> result =
executor.submit(ClassThatImplementsCallable(RETURN_INT));
ClassThatImplementsCallable(RETURN_NOTHING);
Run Code Online (Sandbox Code Playgroud)
要返回null(分别是对Void的引用)或任何其他类型(如String或Integer),我必须使用T,不带任何边界,如下所示:
public static class CallableTest<T> implements Callable<T>{
T value;
CallableTest(T value) {
this.value = value;
}
public T call(){
return value;
}
}
Run Code Online (Sandbox Code Playgroud)
但是,这不是我想要实现的,但是扩展Void并实现其他一些接口也没有意义.
我有一个定义 a 的类__call__,但是当用户在帮助返回时看到对这个“函数”的请求帮助时,他们获得了整个对象和方法,这可能有点令人生畏......我希望帮助看起来如果可能的话,更像是函数的帮助。
我跟踪了inspect模块,但似乎因为我不能从函数类型和/或方法类型继承,所以这可能不可行。我是否遗漏了什么,或者我是否必须重新安排代码以便我动态构建一个真正的 Python 函数对象?
PHP 中的可调用对象可以采用多种形式,例如对象、数组或包含函数名称的字符串。
如果我在变量中得到这样的可调用对象,如何在日志中打印一些用户友好的“定义”。
想想这段代码:
call_user_func($callable);
$logger->log("Provided callable " . (string) $callable . " called");
Run Code Online (Sandbox Code Playgroud)
问题是,这会引发错误,例如数组到字符串的转换错误。打印出有关该可调用内容的有用信息的最佳方法是什么?
我正在尝试编写一种机制,可以同时加载一些模型(使用 ExecutorService)并在所有模型完成后检索它们的结果:
List<Future<Model>> modelFutures = new LinkedList<Future<Model>>();
ExecutorService executor = Executors.newFixedThreadPool(DEFAULT_THREAD_POOL_SIZE);
List<Model> models = new ArrayList<Model>();
for (ClassifierConfig classifierConfig : classifiers) {
try {
final String modelFileName = classifierConfig.name + ".model";
modelFutures.add(executor.submit(new InitModelTask(MODELS_LOCAL_DIR + SEP + modelFileName)));
} catch (Exception e) {
e.printStackTrace();
}
}
for (Future<Model> modelFuture : modelFutures) {
try {
models.add(modelFuture.get(MAX_REQUEST_TIMEOUT_MILLIS, TimeUnit.MILLISECONDS));
} catch (Exception e) {
System.out.println("Timeout occurred when loading models ");
}
}
executor.shutdown();
return models;
Run Code Online (Sandbox Code Playgroud)
任务类如下:
public class InitModelTask implements Callable<Model> {
private String …Run Code Online (Sandbox Code Playgroud) 我刚刚开始学习Java Runnable,我听说过Callables.但是,我非常努力解决这个问题.我想创建一个方法,它将一个函数作为参数(无论是作为a Callable,a Runnable还是其他东西,只要我可以简单地调用函数coolNewFunction(() -> otherFunction(), 100)或类似的简单方法)并且该方法将返回一个数组返回值的otherFunction.例如,假设我定义了该函数
public static int square(int x){
return x * x;
}
Run Code Online (Sandbox Code Playgroud)
然后我可以做一些事情:
coolNewFunction(() -> square(), 100)
Run Code Online (Sandbox Code Playgroud)
这将返回前100个数字及其正方形(即{{1, 1}, {2, 4}, {3, 9}...})的数组.现在,我知道这lambda () -> square()不会起作用,因为square必须传递一个值.我虽然创建了一个100 Runnable秒的数组,每个数组都有下一个参数square,但该方法仍然run()没有返回任何内容.所以,长话短说,一个方法会是什么样的,它会评估另一个函数,它作为一个参数给出,就像square在不同的x值一样,并返回一个该评估的数组?此外,我最好不要开始任何新的线程,虽然这是唯一可以实现这一点的方法.最后,我不想以square特殊方式(最好)实现(或其他)功能.
我尝试推断可调用模板参数的类型,不幸的是没有成功:
template<typename callable, typename T_out >
class A
{};
template<typename callable>
auto make_A( callable f )
{
return A<callable, typename std::result_of_t<callable> >{ f };
}
int main()
{
make_A( []( float f ){ return f;} );
}
Run Code Online (Sandbox Code Playgroud)
上面的代码导致以下错误:
error: implicit instantiation of undefined template 'std::__1::result_of<(lambda at /Users/arirasch/WWU/dev/xcode/tests/tests/main.cpp:31:11)>'
template <class _Tp> using result_of_t = typename result_of<_Tp>::type;
Run Code Online (Sandbox Code Playgroud)
有谁知道如何修理它?
提前谢谢了。
我正在尝试使用泛型(我第一次尝试使用泛型)并使用ExecutorService来实现“ TaskExecutor”。
这是我的“ TaskExecutor”类:
public class ExecuteAlerterTask<T> {
public List<T> process(String executorName, Callable<T> task) throws ExecutionException, InterruptedException {
final ThreadFactory threadFactory = new ThreadFactoryBuilder()
.setNameFormat(executorName + "-%d")
.setDaemon(true)
.build();
ExecutorService executor = Executors.newFixedThreadPool(10, threadFactory);
Collection<Future<T>> futures = new ArrayList<>();
IntStream.range(1, 10).forEach(i -> {
Future<T> future = executor.submit(task);
futures.add(future);
});
List<T> result = new ArrayList<>();
for (Future<T> f : futures) {
result.add(f.get());
}
executor.shutdown();
return result;
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的运行方式:
@Test
public void process() throws Exception {
Callable<String> callable = () -> …Run Code Online (Sandbox Code Playgroud) 这是我需要做的一个最小的例子:
from typing import Callable, Any
class Data:
pass
class SpecificData(Data):
pass
class Event:
pass
class SpecificEvent(Event):
pass
def detect_specific_event(data: SpecificData, other_info: str) -> SpecificEvent:
return SpecificEvent()
def run_detection(callback: Callable[[Data, Any], Event]) -> None:
return
run_detection(detect_specific_event)
Run Code Online (Sandbox Code Playgroud)
现在我收到警告:
Expected type '(Data, Any) -> Event', got '(data: SpecificData, other_info: str) -> SpecificEvent' instead
Run Code Online (Sandbox Code Playgroud)
对我来说,这个警告似乎没有意义,因为 SpecificData 和 SpecificEvent 分别是 Data 和 Event 的子类型,所以一切都应该没问题。有没有办法让这个工作如我所期望的那样?我的想法是能够拥有类似的东西:
class OtherSpecificData(Data):
pass
class OtherSpecificEvent(Event):
pass
def detect_other_event(data: OtherSpecificData, other_info: str) -> OtherSpecificEvent:
return OtherSpecificEvent()
run_detection(detect_other_event)
Run Code Online (Sandbox Code Playgroud)
所以run_detection功能尽可能通用。现在这给出了与上面相同的警告。
假设我有一个这样的课程
class MyClass(AnotherClass):
def __init__(self, arg1, arg2):
self.arg1 = arg1
self.arg2 = arg2
def f(self):
#dostuff
Run Code Online (Sandbox Code Playgroud)
我有字符串"我的班级"
str = "my class"
Run Code Online (Sandbox Code Playgroud)
我可以做这个:
class_name_from_str = str.title().replace(" ", "") # now class_name_from_str is "MyClass"
Run Code Online (Sandbox Code Playgroud)
我怎么能让class_name_from_str可调用?我想要这样的东西:
callable_obj = some_process(class_name_from_str)
o = callable_obj(arg1, arg2)
o.f()
Run Code Online (Sandbox Code Playgroud)
顺便说一句,我正在使用Python 2.7
更新:正如Matti Virkkunen在评论中建议的那样,一个好的解决方案是创建一个dict来映射字符串和类
my_calls_dict = {'my class' : MyClass, 'my other class' : MyOtherClass}
Run Code Online (Sandbox Code Playgroud)