Skip to main content
 首页 » 编程设计

python之我可以在 Python 中创建类方法来接受此类类型的参数吗

2024年11月24日8shanyou

我想说明的是,有些方法采用相同类型的参数,比如这个函数。

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

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 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}")