定义一个带类型的列表

37 投票
7 回答
100899 浏览
提问于 2025-04-15 17:09

我来自Java,想要做一些像这样的数据传输对象(DTO):

class ErrorDefinition():
    code = ''
    message = ''
    exception = ''

class ResponseDTO():
    sucess = True
    errors = list() # How do I say it that it is directly of the ErrorDefinition() type, to not import it every time that I'm going to append an error definition?

或者有没有更好的方法来实现这个呢?

7 个回答

2

现在你可以通过使用类型提示来实现这一点,方法是在__init__函数中指定类型。这里有个简单的例子:

class Foo:
    def __init__(self, value: int):
        self.value = value


class Bar:
    def __init__(self, values: List[Foo]):
        self.values = values

通过这样做,我们知道Barvalues应该是一个指向Foo的列表,而Foovalue应该是一个整数。接下来看看如果我们错误使用会发生什么:

foo = Foo(1)
print(foo.value.split()) 
#               ^^^^^ Hint warning: Unresolved attribute reference 'split' for class 'int'

bar = Bar([foo])
print(bar.values[0] + 2) 
#     ^^^^^^^^^^^^^ Hint warnings: Expected type 'int', got 'Foo' instead 
66

从Python 3.5开始,你可以给列表添加类型。

https://docs.python.org/3/library/typing.html

from typing import List

vector: List[float] = list()

或者

from typing import List

vector: List[float] = []

Python是一种动态类型的语言,不过你可以查看这个链接了解更多:https://www.python.org/dev/peps/pep-0484/

给代码添加类型可以让代码更容易阅读,也更容易理解,还能更好地利用你的开发工具,帮助你写出更高质量的软件。我想这就是为什么它会出现在PEP(Python增强提案)里的原因。

2

errors = list() # 我该怎么说它是直接属于ErrorDefinition()类型的,这样我就不用每次添加错误定义时都导入它?

我不太明白你在这个评论中想表达什么,不过如果我理解正确的话,最好的办法是定义一个方法来添加错误。

class ResponseDTO(object): # New style classes are just better, use them.

    def __init__(self):
        self.success = True # That's the idiomatic way to define an instance member.
        self.errors = [] # Empty list literal, equivalent to list() and more idiomatic.

    def append_error(self, code, message, exception):
        self.success = False
        self.errors.append(ErrorDefinition(code, message, exception))

撰写回答