相关疑难解决方法(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万
查看次数

如何在PEP484之后的方法参数中设置与类相同的类型?

我的问题与新的Python类型提示有关.我正在尝试在对象的方法中添加一个类型提示,该方法具有相同类型的对象的参数,但PyCharm将我标记为error(unresolved reference 'Foo').问题如下:

class Foo:

    def foo_method(self, other_foo: Foo):
        return "Hello World!"
Run Code Online (Sandbox Code Playgroud)

所以问题是如何other_foo正确定义参数类型.也许__class__是对的?

python oop types pycharm python-3.x

5
推荐指数
1
解决办法
504
查看次数

注释 Python3 中静态方法的返回类型

我开始使用更多 Python3 的类型支持,我希望能够注释staticmethods作为替代构造函数的返回类型。

下面是一个最小的例子;如果我包含注释,它会失败:

def from_other_datastructure(json_data: str) -> MyThing:
    NameError: name 'MyThing' is not defined
Run Code Online (Sandbox Code Playgroud)
import typing


class MyThing:
    def __init__(self, items: typing.List[int]):
        self.items = items

    @staticmethod
    def from_other_datastructure(json_data: str):
        return MyThing(
            [int(d) for d in json_data.split(',')]
        )

if __name__ == '__main__':
    s1 = MyThing([1, 2, 3])

    s2 = MyThing.from_other_datastructure("2,3,4")
Run Code Online (Sandbox Code Playgroud)

那么如何在为类型注释定义类之前引用类呢?

python-3.x

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

如何为自定义类的参数指定Type Hint?

假设我创建了一个下面定义的类,并在其上调用了方法:

class Student:

    def __init__(self, name):
        self.name = name
        self.friends = []

    def add_friend(self, new_friend: Student):
        self.friends.append(new_friend)

student1 = Student("Brian")
student2 = Student("Kate")
student1.add_friend(student2)
Run Code Online (Sandbox Code Playgroud)

该方法add_friend有一个称为的参数new_friend,它是一个Student对象。如何使用类型提示进行指定?我假设您只需要简单地输入类的名称即可,new_friend: Student但这是行不通的。运行它时,我得到一个NameError: name 'Student' is not defined。我也尝试过new_friend: __main__.Student,但这给了我同样的错误。我究竟做错了什么?

python types function type-hinting python-3.x

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

标签 统计

python-3.x ×4

python ×3

pycharm ×2

types ×2

function ×1

oop ×1

python-3.5 ×1

type-hinting ×1

typing ×1