Get Field Names in Python: dir() & vars()
You can retrieve the field name in Python using the following method.
- display the contents
class MyClass:
field1 = 'value1'
field2 = 'value2'
fields = [attr for attr in dir(MyClass) if not callable(getattr(MyClass, attr)) and not attr.startswith('__')]
print(fields) # ['field1', 'field2']
- retrieve a dictionary containing all local variables declared in the current scope
class MyClass:
field1 = 'value1'
field2 = 'value2'
obj = MyClass()
fields = list(vars(obj).keys())
print(fields) # ['field1', 'field2']
- dictionary
class MyClass:
field1 = 'value1'
field2 = 'value2'
obj = MyClass()
fields = list(obj.__dict__.keys())
print(fields) # ['field1', 'field2']
These methods are suitable for instances of regular classes, but may not be applicable to special objects such as built-in types and functions.