0

I want to get all the attributes of an object in Python I have defined myself to create a string representation. I want to prevent writing it by hand and filling in all the variables myself, so adding/removing attributes in the future does not amount to mistakes.

For example, in the code below I am looking for a way to retrieve all the attributes I have defined myself: email, password and birthday.

Is there a way to do this in Python?

class Account:
    def __init__(self, email, password, birthday):
        self.email = email
        self.password = password
        self.birthday = birthday

    def __str__(self):
        delim = ","
        # I want to prevent writing this all out
        return f"{self.email}{delim}{self.password}{delim}{self.birthday}"


print(Account("manfred@gmail.com", "hunter2", 3))
  • In this case, just use `self.__dict__` or equivalently, `vars(self)`, both return the object's namespace, which is a `dict` mapping attribute names to attribute values – juanpa.arrivillaga Apr 16 '21 at 22:26

2 Answers2

0

You could use a list comprehension: You need to define an instance of your class:

A = Account("manfred@gmail.com", "hunter2", 3)
{i:getattr(A, i) for i in dir(A) if not i.startswith("_")}

{'birthday': 3, 'email': 'manfred@gmail.com', 'password': 'hunter2'}
Onyambu
  • 67,392
  • 3
  • 24
  • 53
0

Try something like this

list(Account("manfred@gmail.com", "hunter2", 3).__dict__.values())
wuerfelfreak
  • 2,363
  • 1
  • 14
  • 29