python 定义一个类型的列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1924469/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Define a list with type
提问by panchicore
I come from Java, and I want to do some data transfer objects(DTOs) like this:
我来自 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?
Or is there a better way to do this?
或者有没有更好的方法来做到这一点?
采纳答案by ddaa
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?
errors = list() # 如何说它直接属于 ErrorDefinition() 类型,而不是每次我要附加错误定义时都导入它?
I am not sure what you are trying to say in this comment, but if I understand right, the best way to get something close is to define a method to add an error.
我不确定您在此评论中想说什么,但如果我理解正确,最好的方法是定义一个添加错误的方法。
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))
回答by Vladimir Gritsenko
Python is dynamically typed, and you just don't declare types for variables like you do in Java. The official tutorialis highly suggested reading at this stage.
Python 是动态类型的,您只是不像在 Java 中那样为变量声明类型。强烈建议在此阶段阅读官方教程。
回答by John Machin
Please explain what you mean by "import it every time".
请解释“每次都导入”是什么意思。
You need to reconsider using class-level attributes before you have explored exactly what they do, especially when you use mutable types like lists. Consider this:
在深入研究它们的作用之前,您需要重新考虑使用类级属性,尤其是当您使用列表等可变类型时。考虑一下:
>>> class Borg(object):
... alist = list()
...
>>> a = Borg()
>>> b = Borg()
>>> a.alist.append('qwerty')
>>> a.alist
['qwerty']
>>> b.alist
['qwerty']
>>>
Not what you wanted? Use the usual Python idiom of setting up what you need in the class's __init__
method:
不是你想要的?使用通常的 Python 习惯用法在类的__init__
方法中设置您需要的内容:
>>> class Normal(object):
... def __init__(self):
... self.alist = list()
...
>>> x = Normal()
>>> y = Normal()
>>> x.alist.append('frobozz')
>>> x.alist
['frobozz']
>>> y.alist
[]
>>>
回答by Yuchen Zhong
You can achieve this now with type hintby specifying the type from the __init__
function. Just as a simple example:
您现在可以通过指定函数的类型来使用类型提示来实现这一点__init__
。举个简单的例子:
class Foo:
def __init__(self, value: int):
self.value = value
class Bar:
def __init__(self, values: List[Foo]):
self.values = values
With this, we know the values
of Bar
should hold a list of reference to Foo
; and the value
of Foo
should be an integer. Let's see what we have when we use it by mistake:
有了这个,我们知道values
ofBar
应该持有一个引用列表Foo
;并且value
ofFoo
应该是一个整数。让我们看看当我们错误地使用它时我们有什么:
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
回答by John La Rooy
DTO is a design pattern for Java. Trying to use Java semantics in Python is not going to work. You need to step out another level and ask. This is the problem I am trying to solve ... , in Java I would use DTO - how would you approach it using Python?
DTO 是 Java 的一种设计模式。试图在 Python 中使用 Java 语义是行不通的。您需要跨出另一个级别并询问。这是我试图解决的问题......,在 Java 中我会使用 DTO - 你会如何使用 Python 来解决它?
回答by Juan
I'm pretty sure you can't define a type for a list. You're going to need to import ErrorDefinition every time (which looks like the already existing Exception
class).
我很确定您不能为列表定义类型。您每次都需要导入 ErrorDefinition (看起来像已经存在的Exception
类)。