0

I'd like to know if there's a way to get class instance variables that are inside an init.

I've seen something verify close what I am looking for except that I am looking for a way to get instance variables and not class variables. Linked subject: Looping over class variable's attributes in python

Say I have a class such as:

class Identity:
    table = "tb_identity"
    def __init__(self, id="", app_name="", app_code="", state="", criticality=""):
        self.id = id
        self.app_name = trigram_name
        self.app_code = trigram_irt
        self.state = state
        self.criticality = criticality

I'd like to be able to get a list of with instance variables name like:

["id","app_name","app_code","state","criticality"]

With something such as :

members = [getattr(Identity,attr) for attr in dir(Identity) if not attr.startswith("__")]

Im only getting "tb_identity" and not even "table". But that's not the main problem, I am looking for something like:

["id","app_name","app_code","state","criticality"]

Is there any proper way to get these variables inside init ?

Thank you for your time.

Edit: Any way of doing this without instanciation?

  • `list(vars(Identity()))` – Aran-Fey Apr 11 '19 at 09:43
  • Thanks for the answer @Aran-Fey. Do you know if there's any way of doing that without instanciating an object? Here are some other linked subjects: https://stackoverflow.com/questions/61517/python-dictionary-from-an-objects-fields https://stackoverflow.com/questions/2675028/list-attributes-of-an-object – Gaëtan GOUSSEAUD Apr 11 '19 at 09:50
  • 1
    There is a way to do that... but only if you have access to the source code, and you're willing to write some questionable code. – Aran-Fey Apr 11 '19 at 09:52

1 Answers1

0

Try

class Identity:
    table = "tb_identity"
    def __init__(self, id="", app_name="", app_code="", state="", criticality=""):
        self.id = id
        self.app_name = 'trigram_name'
        self.app_code = 'trigram_irt'
        self.state = state
        self.criticality = criticality
        print(self.__dict__.keys())

i = Identity()

Output

dict_keys(['id', 'app_name', 'app_code', 'state', 'criticality'])
balderman
  • 22,927
  • 7
  • 34
  • 52
  • While this does work, it also may return methods that were dynamically added to the instance too. Not there is really a better way, just a gotcha to watch out for. :-) – John Szakmeister Apr 11 '19 at 10:20