我在python 3中有以下代码:
class Position:
def __init__(self, x: int, y: int):
self.x = x
self.y = y
def __add__(self, other: Position) -> Position:
return Position(self.x + other.x, self.y + other.y)
Run Code Online (Sandbox Code Playgroud)
但是我的编辑器(PyCharm)说无法解析引用位置(在_add__方法中).我该如何指定我希望返回类型是类型__add__?
编辑:我认为这实际上是一个PyCharm问题.它实际上使用其警告中的信息和代码完成

但如果我错了,请纠正我,并需要使用其他语法.
如果我有这样的功能:
def foo(name, opts={}):
pass
Run Code Online (Sandbox Code Playgroud)
我想在参数中添加类型提示,我该怎么做?我假设的方式给了我一个语法错误:
def foo(name: str, opts={}: dict) -> str:
pass
Run Code Online (Sandbox Code Playgroud)
以下不会抛出语法错误,但它似乎不是处理这种情况的直观方式:
def foo(name: str, opts: dict={}) -> str:
pass
Run Code Online (Sandbox Code Playgroud)
我在typing文档或Google搜索中找不到任何内容.
编辑:我不知道默认参数在Python中如何工作,但为了这个问题,我将保留上面的例子.一般来说,做以下事情要好得多:
def foo(name: str, opts: dict=None) -> str:
if not opts:
opts={}
pass
Run Code Online (Sandbox Code Playgroud) from dataclasses import dataclass
@dataclass
class InventoryItem:
"""Class for keeping track of an item in inventory."""
name: str | None = None
unit_price: float
quantity_on_hand: int = 0
Run Code Online (Sandbox Code Playgroud)
类型错误: | 不支持的操作数类型:“type”和“NoneType”
Python 3.9
我认为问题是使用最新版本的python,如何解决。
我尝试使用“或”,但没有帮助
据我所知,以下两种类型在 Python 中是等效的:
Optional[Union[A, B]]
Union[A, B, None]
是否有一个明确的约定可供选择,例如 PEP 中的条款?
python ×4
python-3.x ×2
type-hinting ×2
typing ×2
mypy ×1
nonetype ×1
pycharm ×1
python-3.5 ×1
union-types ×1