Skip to main content
 首页 » 编程设计

python之Python 3.x 可以强制方法参数是特定的类实例/对象吗 (阿拉 PHP)

2025年05月04日25qlqwjy

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; 
        ... 
    } 
} 

是否有类似的方法来强制方法参数是 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 的风格是不正确/不优雅/“不是 pythonic”,我应该怎么做?

请您参考如下方法:

不是开箱即用的。但是,您可以合并 parameter annotations使用函数装饰器几乎可以毫不费力地编写自己的装饰器。

但是请记住,duck typing 的整个概念就是要避免这种逻辑。