循环遍历python中的对象(类实例)属性并打印它们

时间:2018-04-17 16:53:42

标签: python oop properties

在python中,如何在不显式调用对象的属性的情况下访问对象的属性?并打印这些属性?

例如:

class MyClass:
     def __init__(self):
     self.prop1 = None
     self.prop2 = 10

     def print_properties(self):
     # Print the property name and value

example_a = MyClass()
example_a.print_properties()

期望的输出:

prop1: None
prop2: 10

using object.dict.keys()不同,因为有人指出不建议访问private __dict__方法。 Linked posted是2008回答,并没有定义如何遍历对象。

2 个答案:

答案 0 :(得分:1)

我找到一个基本对象,以下内部函数完成任务:

def print_properties(self):
    for attr in self.__dict__:
        print(attr, ': ', self.__dict__[attr])

所有在一起:

>>class MyClass:
    def __init__(self):
        self.prop1 = None
        self.prop2 = 10
    def print_properties(self):
        for attr in vars(self):
             print(attr, ': ', vars(self)[attr])

>>example_a = MyClass()
>>example_a.print_properties()
prop1 :  None
prop2 :  10

>>example_a.prop1 = 'Bananas'
>>example_a.print_properties()
prop1 :  Bananas
prop2 :  10

答案 1 :(得分:0)

尝试不使用私人__dict__, 你有python内置函数叫vars()

def print_properties(self):
    for prop, value in vars(self).items():
        print(prop, ":", value) # or use format

解释vars,来自pythom官方文档:

  

返回模块,类,实例或任何内容的__dict__属性   具有__dict__属性的其他对象。

     

模块和实例等对象具有可更新的__dict__   属性;但是,其他对象可能会对其进行写入限制   __dict__属性(例如,新式类使用dictproxy来防止直接字典更新)。

     

如果没有参数,vars()就像locals()一样。请注意,当地人   字典仅对本地的更新有用   字典被忽略了。