如何在Python中为参数分配类型?
我有一个名为 triangulo 的类和一个名为 coord 的类。因此,在创建三角形的新实例的方式中,我传递了三个顶点,例如
t= triangle( V1, V2, V3)
因此,对于文档,我想以这种方式编写三角形类
class triangulo( object ):
def __init__(self, a:coord, b:coord, c:coord)->None:
"""Constructor
"""
self.A= a
self.B= b
self.C= c
class coord( object ):
def __init__( self, x, y ):
self.x= x
self.y= y
但是当我尝试导入这个库时,我收到此错误
NameError: name 'coord' is not Defined
所以问题是:如何让 python 接受顶点作为数据类型?
I have a class named triangulo, and a class named coord. So, in a way to create a new instance of triangle, I pass three vertex like
t= triangle( V1, V2, V3)
So, for documentation, I want to write the class triangle in this way
class triangulo( object ):
def __init__(self, a:coord, b:coord, c:coord)->None:
"""Constructor
"""
self.A= a
self.B= b
self.C= c
class coord( object ):
def __init__( self, x, y ):
self.x= x
self.y= y
But when I try to import this library I get this error
NameError: name 'coord' is not defined
So the question is: How can I make python accept vertex as a type of data?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您需要在使用该类之前声明它!所以将
coord
类放在triangulo
之上就可以解决问题You need to declare the class before using it! so putting
coord
class on the top oftriangulo
will solve the problem您可以将类的名称用引号引起来
,也可以 使用
__future__
import 自动执行此操作from __future__ import 注解
有效地将所有类型签名括在引号中,以防止出现此问题。只要您不在运行时反射性地查看类型注释(使用诸如 MyClass.__annotations__ 之类的东西),您甚至不会注意到,并且您的类型检查器会工作得更好。You can either wrap the name of the class in quotes
or you can use a
__future__
import to do so automaticallyfrom __future__ import annotations
effectively wraps all type signatures in quotation marks to prevent this exact problem. As long as you're not reflexively viewing type annotations at runtime (with something likeMyClass.__annotations__
), you won't even notice, and your type checker will work better.请注意,类型提示可以是一个类或一个类型(在您的情况下顶点是一个类):
更多详细信息请参见 https://www.python.org/dev/peps/pep-0483/
Note that the type hint can be a class or a type (in your case vertex is a class):
More details at https://www.python.org/dev/peps/pep-0483/