Home > other >  Python - How to store class variables to array in defined order [duplicate]
Python - How to store class variables to array in defined order [duplicate]

Time:09-17

I have this simple Python code

class Person:
 name = ""
 surname = ""
 age = ""

def __init__(self):
  arr = #I want something like this ['name', 'surname', 'age']

How do I achieve putting that variables in order that I want (['name', 'surname', 'age']) to array? Without "initializing" them first with "self"? Thanks.

Edit: I need them in exact order how I defined them, not alphabetical order.

CodePudding user response:

Maybe something like the below with __dict__:

class Person:
    name = ""
    surname = ""
    age = ""

    def __init__(self):
        arr = [attr for attr in Person.__dict__ if ('_' not in attr) & (not callable(getattr(Person, attr)))]
        print(arr)

Person()

Output:

['name', 'surname', 'age']
  • Related