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

问题描述 投票:1回答:2

我想指出,某些方法采用相同类型的参数,就像这个函数一样。

我试着通过动物的例子来解释

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

python python-3.x types
2个回答
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}")

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}")
© www.soinside.com 2019 - 2024. All rights reserved.