我有一个类动物,有几个属性,如:
class Animal(object):
def __init__(self):
self.legs = 2
self.name = 'Dog'
self.color= 'Spotted'
self.smell= 'Alot'
self.age = 10
self.kids = 0
#many more...
Run Code Online (Sandbox Code Playgroud)
我现在想要将所有这些属性打印到文本文件中.我现在这样做的丑陋方式就像:
animal=Animal()
output = 'legs:%d, name:%s, color:%s, smell:%s, age:%d, kids:%d' % (animal.legs, animal.name, animal.color, animal.smell, animal.age, animal.kids,)
Run Code Online (Sandbox Code Playgroud)
有更好的Pythonic方法吗?
Joc*_*zel 272
在这个简单的例子中,您可以使用vars():
an = Animal()
attrs = vars(an)
# {'kids': 0, 'name': 'Dog', 'color': 'Spotted', 'age': 10, 'legs': 2, 'smell': 'Alot'}
# now dump this in some way or another
print ', '.join("%s: %s" % item for item in attrs.items())
Run Code Online (Sandbox Code Playgroud)
如果你想在磁盘上存储Python对象,你应该看看shelve - Python对象持久性.
Zau*_*bov 68
另一种方法是调用该dir()函数(请参阅https://docs.python.org/2/library/functions.html#dir).
a = Animal()
dir(a)
>>>
['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__',
'__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__',
'__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__',
'__weakref__', 'age', 'color', 'kids', 'legs', 'name', 'smell']
Run Code Online (Sandbox Code Playgroud)
请注意,dir()尝试访问可能达到的任何属性.
然后您可以访问属性,例如通过使用双下划线进行过滤:
attributes = [attr for attr in dir(a)
if not attr.startswith('__')]
Run Code Online (Sandbox Code Playgroud)
这只是可以做的事情的一个例子dir(),请检查其他答案以获得正确的方法.
Urj*_*jit 56
也许你正在寻找这样的东西?
>>> class MyTest:
def __init__ (self):
self.value = 3
>>> myobj = MyTest()
>>> myobj.__dict__
{'value': 3}
Run Code Online (Sandbox Code Playgroud)
试试ppretty:
from ppretty import ppretty
class Animal(object):
def __init__(self):
self.legs = 2
self.name = 'Dog'
self.color= 'Spotted'
self.smell= 'Alot'
self.age = 10
self.kids = 0
print ppretty(Animal(), seq_length=10)
Run Code Online (Sandbox Code Playgroud)
输出:
__main__.Animal(age = 10, color = 'Spotted', kids = 0, legs = 2, name = 'Dog', smell = 'Alot')
Run Code Online (Sandbox Code Playgroud)
这是完整的代码.结果正是你想要的.
class Animal(object):
def __init__(self):
self.legs = 2
self.name = 'Dog'
self.color= 'Spotted'
self.smell= 'Alot'
self.age = 10
self.kids = 0
if __name__ == '__main__':
animal = Animal()
temp = vars(animal)
for item in temp:
print item , ' : ' , temp[item]
#print item , ' : ', temp[item] ,
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
205978 次 |
| 最近记录: |