如何访问使用@property装饰器注释的方法的类型提示?
通常,这非常简单:
>>> class Foo:
... def bar(self) -> str:
... pass
...
>>> import typing
>>> typing.get_type_hints(Foo.bar)
{'return': <class 'str'>}
Run Code Online (Sandbox Code Playgroud)
但是一旦bar被注释@property并制作成属性对象,它就不明显了:
>>> class Foo:
... @property
... def bar(self) -> str:
... pass
...
>>> import typing
>>> typing.get_type_hints(Foo.bar)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/local/Cellar/python3/3.6.4_2/Frameworks/Python.framework/Versions/3.6/lib/python3.6/typing.py", line 1527, in get_type_hints
'or function.'.format(obj))
TypeError: <property object at 0x1050fcc28> is not a module, class, method, or function.
>>> typing.get_type_hints(Foo.bar.__get__)
{}
Run Code Online (Sandbox Code Playgroud) 我很难理解Java中的方差是如何工作的.
在以下示例中,我定义了一个函数test,这需要Consumer.函数的定义没有逆变,所以我希望它Consumer<Object>不是一个子类型Consumer<Pair<Animal, Animal>>.然而,代码编译,测试接受lambda Variance:::superAction.
我错过了什么?
import org.apache.commons.lang3.tuple.ImmutablePair;
import org.apache.commons.lang3.tuple.Pair;
import java.util.function.Consumer;
public class Variance {
public static void main(String[] args) {
test(Variance::exactMatchAction);
test(Variance::superAction);
}
private static void exactMatchAction(Pair<Animal, Animal> pair) {
System.out.println(pair.getLeft().getClass().getName());
}
private static void superAction(Object obj) {
System.out.println(obj.getClass().getName());
}
private static void test(Consumer<Pair<Animal, Animal>> action) {
action.accept(ImmutablePair.of(new Animal(), new Animal()));
action.accept(ImmutablePair.of(new Dog(), new Dog()));
}
static class Animal { }
static class Dog extends Animal { }
}
Run Code Online (Sandbox Code Playgroud)
编辑:Per …