类型提示:类类型的参数

2024-05-15 09:01:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我在定义一种方法

def foo_my_class(my_class: ???, bar: str) -> None:
    """ Operate on my_class """

我想知道,如何使用类型提示功能来指定类应该在第一个参数中传递。在

基本上,我应该用什么代替???标记在那里?谢谢。在

UPD:这里有更多的代码可以更具体地说明我要实现的目标。在

^{pr2}$

Tags: 方法标记功能none类型参数定义foo
2条回答

我可能错了,因为我在Python3.5中还没有深入研究过,但是看看documentation你应该可以用typing.Optional来完成。一个简单的例子。在

>>> from typing import Optional
>>> 
>>> class MyClass(object):
>>>     def __init__(self):
>>>         self.a = 1
>>> 
>>> O = Optional[MyClass]
>>> 
>>> def test(x: O) -> int:
>>>     return x.a
>>> 
>>> myclass = MyClass()
>>> print test(myclass)
1

希望有帮助。在

你只需要使用类本身。在

def foo_my_class(my_class: MyClass, bar: str) -> None:

来自the PEP(重点是我的):

Type hints may be built-in classes (including those defined in standard library or third-party extension modules), abstract base classes, types available in the types module, and user-defined classes (including those defined in the standard library or third-party modules).

相关问题 更多 >