我可以在Python中使用类方法来获取此类类型的参数吗?

我可以在Python中使用类方法来获取此类类型的参数吗?,python,python-3.x,types,Python,Python 3.x,Types,我想指定,某些方法采用相同类型的参数,比如这个函数 我试着用动物的例子来解释 类动物: 定义初始化(self,名称:str): self.name=名称 def说你好(自我,动物:动物): 打印(f“Hi{animal.name}”) str类型的名称不会产生任何问题,但无法识别动物: NameError: name 'Animal' is not defined 我使用PyCharm和Python3.7使用类型定义一个类型。NewType并从中继承: from typing import

我想指定,某些方法采用相同类型的参数,比如这个函数

我试着用动物的例子来解释

类动物:
定义初始化(self,名称:str):
self.name=名称
def说你好(自我,动物:动物):
打印(f“Hi{animal.name}”)
str类型的名称不会产生任何问题,但无法识别动物:

NameError: name 'Animal' is not defined

我使用PyCharm和Python3.7使用
类型定义一个类型。NewType
并从中继承:

from typing import NewType

AnimalType = NewType('AnimalType', object)

class Animal:
    def __init__(self, name: str):
        self.name = name

    def say_hello(self, animal: AnimalType):
        print(f"Hi {animal.name}")

类名不可用,因为此时尚未定义它。自Python 3.7以来,您可以通过在任何导入或代码之前添加此行来启用注释()的延迟评估:

from __future__ import annotations
或者,您可以使用字符串注释,大多数类型检查器都应该识别这些注释,包括PyCharm中内置的注释:

class Animal:
    def __init__(self, name: str):  # this annotation can be left as a class
        self.name = name

    def say_hello(self, animal: 'Animal'):  # this one is itself a string
        print(f"Hi {animal.name}")

是的,这是我们想要的方法。静态类型检查器/运行时检查器会理解这一点。这不能满足@AZW的需要,因为
Animal('Tom')。say_hello(Animal('Jerry'))
无法通过静态类型检查器。