[英]In Python how can I create a method in a class that assigns values to attributes
[英]How can I print every values of each attributes of a class in Python
我想打印一個類的每個值,但是我不知道該怎么做。 我了解為什么我的方法無法奏效。
class test:
def __init__(self, a = 1, b = 2, c = 3):
self.a = a
self.b = b
self.c = c
classobject = test()
for attr in dir(classobject) :
if not attr.startswith('__'):
print(str(attr) + ' value= ' + classobject.attr)
我收到錯誤AttributeError: 'test' object has no attribute 'attr'
classobject.attr
是專門尋找一個名為屬性attr
在classobject
。
attr
在運行時不會被適當的值神奇地替換。
您需要的是getattr函數:
print(str(attr) + ' value= ' + getattr(classobject, attr))
你可以做
print(test.__dict__)
基本上可以刮除對象的所有屬性。 這可能不是您想要的,但這至少是您想要的超集。 我想如果您有一個明確關心的屬性列表,則可以按鍵進行過濾。
classobject = test()
attrs = vars(classobject)
for key,value in attrs.items():
print (str(key) + ' value= ' +str(value))
結果:
值= 1
b值= 2
c值= 3
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.