[英]Output object attributes and values in alphabetical order
I need to generate an export (csv) of a series of simple objects like this: 我需要生成一系列简单对象的导出(csv),如下所示:
class trx:
def __init__(self,
file_name='',
bank='',
trans_type='',
account=''):
self.filename = file_name
self.bank = bank
self.trans_type = trans_type
self.account = account
What is the simplest way to list the attribute/value pairs in order by attribute? 按属性顺序列出属性/值对的最简单方法是什么?
__dict__
changes order every time. __dict__
每次都会更改顺序。
You could use vars()
on self
, then sort the items: 您可以在
self
上使用vars()
,然后对项目进行排序:
sorted(vars(self).items())
This then gives you a sorted list of (attributename, value)
pairs. 然后,这为您提供了
(attributename, value)
对的排序列表。
However, if your class is little more than a container for 4 related datapoints, then consider using a namedtuple
class : 但是,如果您的类只不过是用于容纳4个相关数据点的容器,请考虑使用
namedtuple
类 :
from collections import namedtuple
TRX = namedtuple('TRX', ('file_name', 'bank', 'trans_type', 'account'))
This lists the attributes in named order, always: 这始终按命名顺序列出属性:
>>> from collections import namedtuple
>>> TRX = namedtuple('TRX', ('file_name', 'bank', 'trans_type', 'account'))
>>> TRX('foo.txt', 'Bar PLC', 'withdrawal', '1234xyz')
TRX(file_name='foo.txt', bank='Bar PLC', trans_type='withdrawal', account='1234xyz')
Because the instances are sequences (a subclass of tuple
in fact) you can pass these directly to a csv.writer().writerow()
call ; 因为实例是序列(实际上是
tuple
的子类),所以您可以将它们直接传递给csv.writer().writerow()
调用 ; at the same time you can use instance.bank
or instance.file_name
to access the fields. 同时,您可以使用
instance.bank
或instance.file_name
来访问字段。
Another alternative is to use dictionaries , and use csv.DictWriter()
to handle the order (the fieldnames
argument determines the order). 另一种选择是使用字典 ,然后使用
csv.DictWriter()
处理顺序( fieldnames
参数确定顺序)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.