【问题标题】:specify the type inside a class method在类方法中指定类型
【发布时间】:2021-12-09 00:28:18
【问题描述】:

正确指定方法参数类型的pythonic方法是什么?

检查How do Python functions handle the types of the parameters that you pass in?How do I ensure parameter is correct type in Python? 仅适用于原始数据类型。

考虑下面的最小示例,我想将相同类型的对象传递给方法。这不起作用,因为该方法是在类中定义的。

class num:
    def __init__(self,val:int) -> None:
        self.x=val
    def print(self,other:num) -> None:
        pass

def main():
    n=num(3)
    n.print()

main()

【问题讨论】:

    标签: python-3.x parameter-passing readability


    【解决方案1】:

    你可以使用forward references:

    class num:
        def __init__(self,val:int) -> None:
            self.x=val
        def print(self,other:'num') -> None:
            pass
    
    

    这是可行的,因为 Python(以及任何符合 PEP 484 的检查器)会理解您的提示并适当地注册它,这是一种常见的情况。

    【讨论】:

      猜你喜欢
      • 2022-01-18
      • 2011-03-11
      • 2016-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-25
      • 2022-07-28
      相关资源
      最近更新 更多