Python是动态类型的,它没有提供方法参数的类型提示。但是,PHP也是动态类型的,它确实提供了一个类型提示--暗示一个方法参数至少是一个类的实例(或者是一个从定义的类继承的类的实例)。
public class Foo()
{
public function __construct($qux, ...)
{
$this->qux = qux;
...
}
}
public class Bar()
{
// "Type Hinting" done here enforcing
// that $baz is an instance of Foo
public function __construct(Foo $baz, ...)
{
$this->baz = $baz;
...
}
}
是否有类似的方法来强制一个方法param是Python中的一个特定实例?
如果不是,那么是否应该简单地声明一下呢?
class Foo(object):
def __init__(self, qux=None, ...):
self.qux = qux
...
class Bar(object):
def __init__(self, baz=None, ...):
# "Type Hinting" done here as `assert`, and
# requires catch of AssertionError elsewhere
assert isinstance(baz, Foo)
self.baz = baz
...
如果这是使用assert
的方式是不正确的/不雅/“不是琵琶”,我应该做什么呢?
发布于 2014-04-14 14:09:07
发布于 2014-04-14 14:39:51
Python中有一个很强的习惯,可以接受鸭型成语,在本例中,这意味着您将调用来自baz
对象的适当属性,而不显式地检查其类型。这有许多好处,包括对多态性的更好支持,以及可读性更强/更少冗长的代码。
如果试图访问对象不支持的属性,则会引发AttributeError
异常。因此,您可以将其放置在try/except
块中,并在适当时捕获任何AttributeError
--这是另一个称为“请求宽恕比许可更容易”的Python成语的特征。
try:
baz.foo
except AttributeError:
# handle the exception
其他一些涉及这个主题的问题
https://stackoverflow.com/questions/23071213
复制