相关疑难解决方法(0)

如何指定方法的返回类型与python中的类本身相同?

我在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问题.它实际上使用其警告中的信息和代码完成

但如果我错了,请纠正我,并需要使用其他语法.

python typing pycharm python-3.x python-3.5

277
推荐指数
7
解决办法
4万
查看次数

在Python中使用类型提示添加默认参数值

如果我有这样的功能:

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)

python type-hinting python-3.x

169
推荐指数
3
解决办法
5万
查看次数

类型错误: | 不支持的操作数类型:“type”和“NoneType”

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 typing nonetype

7
推荐指数
1
解决办法
2万
查看次数

可选 [Union] 与 Union[None] 的首选 Python 键入语法

据我所知,以下两种类型在 Python 中是等效的:

Optional[Union[A, B]]

Union[A, B, None]

是否有一个明确的约定可供选择,例如 PEP 中的条款?

python type-hinting mypy union-types python-typing

6
推荐指数
0
解决办法
2738
查看次数