这是我的代码:
function phpwtf(string $s) {
echo "$s\n";
}
phpwtf("Type hinting is da bomb");
Run Code Online (Sandbox Code Playgroud)
导致此错误:
可捕获的致命错误:传递给phpwtf()的参数1必须是字符串的实例,给出字符串
看到PHP在同一口气中识别并拒绝所需的类型,这不仅仅是一点Orwellian.该死的有五盏灯.
PHP中字符串的类型提示相当于什么?奖励考虑答案,准确解释这里发生了什么.
在构造函数,赋值和方法调用方面,PyCharm IDE非常擅长分析我的源代码并确定每个变量应该是什么类型.我喜欢它,因为它给了我很好的代码完成和参数信息,如果我尝试访问不存在的属性,它会给我警告.
但是当谈到参数时,它什么都不知道.代码完成下拉列表无法显示任何内容,因为它们不知道参数的类型.代码分析无法查找警告.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
peasant = Person("Dennis", 37)
# PyCharm knows that the "peasant" variable is of type Person
peasant.dig_filth() # shows warning -- Person doesn't have a dig_filth method
class King:
def repress(self, peasant):
# PyCharm has no idea what type the "peasant" parameter should be
peasant.knock_over() # no warning even though knock_over doesn't exist
King().repress(peasant)
# Even if I call the method once with a Person instance, …
Run Code Online (Sandbox Code Playgroud) 如果我有这样的功能:
def foo(name, opts={}):
pass
Run Code Online (Sandbox Code Playgroud)
我想在参数中添加类型提示,我该怎么做?我假设的方式给了我一个语法错误:
def foo(name: str, opts={}: dict) -> str:
pass
Run Code Online (Sandbox Code Playgroud)
以下不会抛出语法错误,但它似乎不是处理这种情况的直观方式:
def foo(name: str, opts: dict={}) -> str:
pass
Run Code Online (Sandbox Code Playgroud)
我在typing
文档或Google搜索中找不到任何内容.
编辑:我不知道默认参数在Python中如何工作,但为了这个问题,我将保留上面的例子.一般来说,做以下事情要好得多:
def foo(name: str, opts: dict=None) -> str:
if not opts:
opts={}
pass
Run Code Online (Sandbox Code Playgroud) 以下代码:
<?php
class Type {
}
function foo(Type $t) {
}
foo(null);
?>
Run Code Online (Sandbox Code Playgroud)
在运行时失败:
PHP Fatal error: Argument 1 passed to foo() must not be null
Run Code Online (Sandbox Code Playgroud)
为什么不允许像其他语言一样传递null?
PHP 7引入了返回类型声明.这意味着我现在可以指示返回值是某个类,接口,数组,可调用或新的可阻塞标量类型之一,这对于函数参数是可能的.
function returnHello(): string {
return 'hello';
}
Run Code Online (Sandbox Code Playgroud)
通常情况下,值并不总是存在,并且您可能返回某种类型的某些内容,或者返回null.虽然您可以通过将其默认值设置为null(DateTime $time = null
)来使参数可为空,但似乎没有办法为返回类型执行此操作.确实如此,或者我不知道怎么做?这些不起作用:
function returnHello(): string? {
return 'hello';
}
function returnHello(): string|null {
return 'hello';
}
Run Code Online (Sandbox Code Playgroud) 我在python中有一个函数可以返回a bool
或a list
.有没有办法使用类型提示指定返回类型.
例如,这是正确的方法吗?
def foo(id) -> list or bool:
...
Run Code Online (Sandbox Code Playgroud) 假设我有一个功能:
def get_some_date(some_argument: int=None) -> %datetime_or_None%:
if some_argument is not None and some_argument == 1:
return datetime.utcnow()
else:
return None
Run Code Online (Sandbox Code Playgroud)
如何为可能的内容指定返回类型None
?
请考虑以下代码:
from collections import namedtuple
point = namedtuple("Point", ("x:int", "y:int"))
Run Code Online (Sandbox Code Playgroud)
上面的代码只是一种证明我想要实现的目标的方法.我想namedtuple
用类型提示.
你知道如何达到预期效果的优雅方式吗?
python type-hinting namedtuple python-3.x python-dataclasses
我正在尝试使用抽象基类的Python类型注释来编写一些接口.有没有办法注释可能的类型*args
和**kwargs
?
例如,如何表达函数的合理参数是一个int
还是两个int
?type(args)
给人Tuple
所以我的猜测是,注释类型Union[Tuple[int, int], Tuple[int]]
,但是这是行不通的.
from typing import Union, Tuple
def foo(*args: Union[Tuple[int, int], Tuple[int]]):
try:
i, j = args
return i + j
except ValueError:
assert len(args) == 1
i = args[0]
return i
# ok
print(foo((1,)))
print(foo((1, 2)))
# mypy does not like this
print(foo(1))
print(foo(1, 2))
Run Code Online (Sandbox Code Playgroud)
来自mypy的错误消息:
t.py: note: In function "foo":
t.py:6: error: Unsupported operand types for + ("tuple" and "Union[Tuple[int, int], Tuple[int]]") …
Run Code Online (Sandbox Code Playgroud) type-hinting ×10
python ×7
python-3.x ×5
php ×3
python-3.5 ×3
return-type ×2
namedtuple ×1
nullable ×1
php-7 ×1
pycharm ×1
typechecking ×1
types ×1
typing ×1