使用枚举定义python类
最近,我定义了一个Python类,如下所示使用枚举定义python类,python,class,enums,Python,Class,Enums,最近,我定义了一个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
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中的编码能力
谢谢您可以调用
self.\u eq.\u(其他)
函数中的\u ne.\u
编写数据类的最佳方法因用例而异。但对于您所展示的内容,您不应该重复代码。定义了\uuuu eq\uuu
运算符后,应该在其他地方使用该运算符。(如果你对\uuuuu eq\uuuuu
的定义改变了怎么办?)而且,你不必定义太阳底下的每一种神奇方法。。。只是那些对你有价值的东西
查看此Python神奇方法指南:
另请参见\uu ne\uuuuuu
vs\uuuuu eq\uuuuu
以及如何定义它们的答案:
您还应该研究decorators(特别是
@property
)您多次使用此模式(此处显示的是\uuuu init\uuuu
,它也适用于\uu str\uuu
和\uu repr\uuu
):
最好直接迭代ExampleClass.defaults
中的项目,而不是手动计算索引。这可以通过以下方式实现:
\uuuu eq\uuu
方法可通过以下方式简化:
然后,正如其他人已经说过的,您可以用\uuuuu eq\uuuu
来表示\uuu ne\uuuu
,甚至可以使用=
操作符:
def __ne__(self, other):
return not self == other
我喜欢。我本来会这么做的,但那是蟒蛇吗?只是好奇谢谢。我不知道zip。非常感谢您的回复。如上所述,
\uuu ne\uuu
运算符已更改,以反映其与\uu eq\uu
运算符的对称性。此外,我并不是在定义它们,只是那些可能对我有用的,或者我经常使用的,我想明确说明它们的操作的。最后,在此之前,我使用的是@property
,但我并不特别关心它们的私密性,我只是不喜欢一遍又一遍地写出相同的定义。我很高兴我的建议很受欢迎,但请不要编辑问题中的原始代码(请参阅)@mkrieger1-那个元帖子是专门针对代码评审的,堆栈溢出有不同的系统。@rolfl哦,我刚刚看到了。但是,相同(或至少相似)的原则不适用于这里吗?事实上,这整个问题不比堆栈溢出更适合于代码审查吗?我觉得这整个问题都离题了,因为没有具体的编程问题。。。。而且,整个问题都应该在代码审查时提出,但是,尽管如此,不,同样的原则在这里并不适用——尽管我经常认为它们应该适用。
for ex, default in zip(enums.ExampleEnums, ExampleClass.defaults):
setattr(self, ex.name, kwargs.get(ex.value, default))
def __eq__(self, other):
return all(getattr(self, val.name) == getattr(other, val.name)
for val in enums.ExampleEnums)
def __ne__(self, other):
return not self == other