【发布时间】:2015-09-03 18:23:07
【问题描述】:
最近我定义了一个 Python 类,如下所示。
from datetime import datetime, date, time
import enums
class ExampleClass:
defaults = (-1, "", "", datetime.today(), "", -1, [], "", -1, "", "", [], "")
def __init__(self, **kwargs):
count = 0
for ex in enums.ExampleEnums:
setattr(self, ex.name, kwargs.get(ex.value, ExampleClass.defaults[count]))
count += 1
def __str__(self):
return_string = "Example Object with "
count = 0
for val in enums.ExampleEnums:
if (getattr(self, val.name) != ExampleClass.defaults[count]):
return_string += str("%s: %s, " % (val.name, getattr(self, val.name)))
count += 1
return return_string[:-2]
def __repr__(self):
return_string = ""
count = 0
for val in enums.ExampleEnums:
if (getattr(self, val.name) != ExampleClass.defaults[count]):
return_string += str("%s=%s, " % (val.value, getattr(self, val.name)))
count += 1
return return_string[:-2]
def __eq__(self, other):
for val in enums.ExampleEnums:
if (getattr(self, val.name) != getattr(other, val.name)):
return False
return True
def __ne__(self, other):
for val in enums.ExampleEnums:
if (getattr(self, val.name) == getattr(other, val.name)):
return False
return True
无论如何,我想知道:这是为数据类编写类定义的好方法吗?有什么方法可以改进吗?我不需要任何代码,只需要概括性就可以了,因为我只是将其发布为了解如何提高自己在 Python 中的编码能力的一种方式。
谢谢
【问题讨论】:
-
很高兴我的建议受到好评,但请不要编辑您问题中的原始代码(请参阅What you may and may not do after receiving answers)。
-
@mkrieger1 - 那篇文章是专门针对代码审查的,而 Stack Overflow 有不同的系统。
-
@rolfl 哦,我刚刚看到了。但是相同的(或至少相似的)原则是否适用于这里?
-
实际上,这整个问题不是更适合代码审查而不是堆栈溢出吗?
-
令我震惊的是,这整个问题都是题外话,因为没有具体的编程问题......而且,整个问题应该在代码审查中提出,但是,尽管如此,不,同样的原则在这里并不适用——尽管我经常认为它们应该适用。