Sobes.tech
Junior — Middle

How can you get a list of the object's properties and their values?

sobes.tech AI

Answer from AI

In Python, you can get a list of an object's properties (attributes) and their values using built-in functions:

  • dir(obj) — returns a list of all attributes of the object (including methods and special attributes).
  • vars(obj) — returns a dictionary of the object's attributes and their values (only for instance attributes).
  • obj.__dict__ — similar to vars(), contains the instance's attributes.

Example:

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

p = Person("Alice", 30)

print(dir(p))          # list of all attributes and methods
print(vars(p))         # {'name': 'Alice', 'age': 30}
print(p.__dict__)      # {'name': 'Alice', 'age': 30}

Thus, to get properties and their values, it is convenient to use vars() or __dict__.

How can you get a list of the object's properties and… - sobes.tech