相关疑难解决方法(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:在类定义中使用类自己的类型

以下代码无法按预期工作。显然,我不能在类定义中使用类自己的类型:

class Foo:
    def __init__(self, key :str) -> None:
        self.key = key

    def __eq__(self, other :Foo) -> bool:
        return self.key == other.key

print('should be true: ', Foo('abc') == Foo('abc'))
print('should be false: ', Foo('abc') == Foo('def'))
Run Code Online (Sandbox Code Playgroud)

运行结果如下:

Traceback (most recent call last):
  File "class_own_type.py", line 1, in <module>
    class Foo:
  File "class_own_type.py", line 5, in Foo
    def __eq__(self, other :Foo) -> bool:
NameError: name 'Foo' is not defined
Run Code Online (Sandbox Code Playgroud)

此外,检查代码mypy返回:

class_own_type.py:5: error: Argument 1 of "__eq__" incompatible with supertype …
Run Code Online (Sandbox Code Playgroud)

python type-hinting mypy

17
推荐指数
1
解决办法
7870
查看次数

python中的自引用类?

在Python中,您是否可以拥有成员的类,这些成员本身就是指向同一类类型成员的指针?例如,在C中,您可能在二叉树中具有以下类的节点:

struct node {
    int data;
    struct node* left;
    struct node* right;
} 
Run Code Online (Sandbox Code Playgroud)

你会如何在python中等效地创建它?

python class

3
推荐指数
4
解决办法
3957
查看次数

Python 3.6类型:在赋值之前使用变量

类型/提示/分配的新方法很酷,但我不知道如何使这么简单的事情起作用:

class MyContainer:
    def addMyItem(self, item:MyItem):
        pass

class MyItem:
    def __init__(self, container:MyContainer):
        pass
Run Code Online (Sandbox Code Playgroud)

它抛出一个错误:Using variable 'MyItem' before assignment.到目前为止我发现的最好但超级丑陋的解决方法是:

class MyContainer:
    def addMyItem(self, untypeditem):
        item:MyItem=untypeditem
        pass

class MyItem:
    def __init__(self, container:MyContainer):
        pass
Run Code Online (Sandbox Code Playgroud)

请告诉我,#1原则的语言可以Beautiful is better than ugly更好地解决这个常见的打字问题

python types python-3.x

3
推荐指数
1
解决办法
547
查看次数

标签 统计

python ×4

python-3.x ×2

class ×1

mypy ×1

pycharm ×1

python-3.5 ×1

type-hinting ×1

types ×1

typing ×1