python 类各方法参数_python – 使用类作为其方法中参数的类型提示

我在下面包含的代码会引发以下错误:

NameError: name 'Vector2' is not defined

在这一行:

def Translate (self, pos: Vector2):

为什么Python无法在Translate方法中识别我的Vector2类?

class Vector2:

def __init__(self, x: float, y: float):

self.x = x

self.y = y

def Translate(self, pos: Vector2):

self.x += pos.x

self.y += pos.y

解决方法:

因为当遇到Translate(在编译类主体时),Vector2尚未定义(它当前正在编译,尚未执行名称绑定); Python自然会抱怨.

由于这是一个常见的场景(在该类的主体中类型提示类),您应该使用forward reference将其括在引号中:

class Vector2:

# __init__ as defined

def Translate(self, pos: 'Vector2'):

self.x += pos.x

self.y += pos.y

Python(以及符合PEP 484的任何检查程序)将理解您的提示并适当地注册它.当通过typing.get_type_hints访问__annotations__时,Python确实认识到了这一点:

from typing import get_type_hints

get_type_hints(Vector2(1,2).Translate)

{'pos': __main__.Vector2}

从Python 3.7开始,这已经改变了;见abarnert’s answer below.

标签:type-hinting,python,python-3-x,oop

来源: https://codeday.me/bug/20190916/1807866.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值