Define a list with type

I come from Java and I want to make data transfer objects (DTO) as follows:

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?

+1
source share
5 answers

errors = list () # How can I say that this is directly from the ErrorDefinition () type so as not to import it every time I am going to add an error definition?

I'm not sure what you are trying to say in this comment, but if I understand correctly, the best way to get something close is to determine how to add the error.

 class ResponseDTO(object): # New style classes are just better, use them. def __init__(self): self.success = True # That 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)) 
+1
source

Python is dynamically typed, and you simply do not declare variable types, as in Java. An official guide is strongly recommended to read at this point.

+6
source

I am sure that you cannot determine the type for the list. You will need to import ErrorDefinition each time (which looks like an existing Exception class).

0
source

DTO is a design pattern for Java. Trying to use Java semantics in Python will not work. You need to go to another level and ask. This is the problem I'm trying to solve ..., in Java I would use DTO - how do you approach it with Python?

0
source

Please explain what you mean by import every time.

You need to reconsider the use of class attributes before you know exactly what they are doing, especially if 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 regular Python idiom to customize what you need in the __init__ class method:

 >>> class Normal(object): ... def __init__(self): ... self.alist = list() ... >>> x = Normal() >>> y = Normal() >>> x.alist.append('frobozz') >>> x.alist ['frobozz'] >>> y.alist [] >>> 
0
source

All Articles