0

In python, how can an object's properties be accessed without explicitly calling them? And print those properties?

Ex:

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()

Desired output:

prop1: None
prop2: 10

Different from: using object.dict.keys() as it was pointed out that accessing the private __dict__ methods is not advised. Linked posted is 2008 answer and doesn't define how to iterate through the object.

HSchmachty
  • 307
  • 1
  • 14

2 Answers2

2

I found for a basic object, the following internal function accomplishes the task:

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

All together:

>>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
HSchmachty
  • 307
  • 1
  • 14
1

Try not using private __dict__, you have python built-in function called vars()

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

Explantion of vars, from pythom offical docs:

Return the __dict__ attribute for a module, class, instance, or any other object with a __dict__ attribute.

Objects such as modules and instances have an updateable __dict__ attribute; however, other objects may have write restrictions on their __dict__ attributes (for example, new-style classes use a dictproxy to prevent direct dictionary updates).

Without an argument, vars() acts like locals(). Note, the locals dictionary is only useful for reads since updates to the locals dictionary are ignored.

Emanuel
  • 640
  • 1
  • 7
  • 25