我可以在Python中制作类方法来接受此类类型的参数吗?

时间:2019-04-14 10:16:55

标签: python python-3.x types

我想指定,某些方法采用相同类型的参数,例如此函数。

我试图以动物为例来解释

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

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

类型为str的名称不会出现任何问题,但是无法识别Animal:

NameError: name 'Animal' is not defined

我使用PyCharm和Python 3.7

2 个答案:

答案 0 :(得分:0)

使用typing.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}")

答案 1 :(得分:0)

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

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}")
相关问题