Python:快速而肮脏的数据类型(DTO) [英] Python: Quick and dirty datatypes (DTO)
问题描述
很多时候,我发现自己在编码一些琐碎的数据类型,例如
class Pruefer:
def __init __(self,ident,maxNum = float('inf'),name =):
self.ident = ident
self.maxNum = maxNum
self.name =名称
虽然这非常有用(显然我不想用匿名的三元组代替上面的内容),它也非常简单。
例如,现在,当我想在字典中使用该类时,我必须添加更多样板,例如
< pre class = lang-py prettyprint-override>
def __hash __(self):
返回hash(self.ident,self.maxNum,self.name)
我承认在所有样板课程中可能很难识别一个通用模式,但是我还是想提这个问题:
-
在python中是否有
流行的惯用法来导出具有命名访问器的快速而肮脏的数据类型? -
或者如果没有的话,也许Python大师可能想炫耀一些元类黑客或类工厂,以使我的生活更轻松?
>>>从集合中导入namedtuple
>> Pruefer = namedtuple( Pruefer, ident maxNum name)
>> pr = Pruefer(1,2,3)
>>居民
1
> pr.maxNum
2
>> pr.name
3
>> hash(pr)
2528502973977326415
要提供默认值,您需要做更多的事情...简单的解决方案是使用 __ new __
方法重新定义子类:
>>类Pruefer(namedtuple( Pruefer, ident maxNum name)):
... def __new __(cls,ident,maxNum = float('inf'),name =):
... return super(Pruefer,cls).__ new __(cls,ident,maxNum,name)
...
>> Pruefer(1)
Pruefer(ident = 1,maxNum = inf,name =’’)
Very often, I find myself coding trivial datatypes like
class Pruefer:
def __init__(self, ident, maxNum=float('inf'), name=""):
self.ident = ident
self.maxNum = maxNum
self.name = name
While this is very useful (Clearly I don't want to replace the above with anonymous 3-tuples), it's also very boilerplate.
Now for example, when I want to use the class in a dict, I have to add more boilerplate like
def __hash__(self):
return hash(self.ident, self.maxNum, self.name)
I admit that it might be difficult to recognize a general pattern amongst all my boilerplate classes, but nevertheless I'd like to as this question:
Are there any popular idioms in python to derive quick and dirty datatypes with named accessors?
Or maybe if there are not, maybe a Python guru might want to show off some metaclass hacking or class factory to make my life easier?
>>> from collections import namedtuple
>>> Pruefer = namedtuple("Pruefer", "ident maxNum name")
>>> pr = Pruefer(1,2,3)
>>> pr.ident
1
>>> pr.maxNum
2
>>> pr.name
3
>>> hash(pr)
2528502973977326415
To provide default values, you need to do little bit more... Simple solution is to write subclass with redefinition for __new__
method:
>>> class Pruefer(namedtuple("Pruefer", "ident maxNum name")):
... def __new__(cls, ident, maxNum=float('inf'), name=""):
... return super(Pruefer, cls).__new__(cls, ident, maxNum, name)
...
>>> Pruefer(1)
Pruefer(ident=1, maxNum=inf, name='')
这篇关于Python:快速而肮脏的数据类型(DTO)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!