用typ定义列表

2024-05-26 09:18:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我来自Java,我想做一些类似这样的data transfer objects(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?

还是有更好的办法?


Tags: tomessagedataobjectsthatexceptioncodeit
3条回答

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?

我不确定你在评论中想说什么,但如果我理解正确,最好的接近方法是定义一个方法来添加一个错误。

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))

DTO是Java的一种设计模式。尝试在Python中使用Java语义是行不通的。你需要跨出另一层去问。这就是我要解决的问题。。。,在Java中,我将使用DTO—您将如何使用Python来处理它?

Python是动态类型的,您只是不像Java那样为变量声明类型。^现阶段强烈建议阅读{a1}。

相关问题 更多 >