Getting attributes of a class
Try the inspect module. getmembers
and the various tests should be helpful.
EDIT:
For example,
class MyClass(object):
a = '12'
b = '34'
def myfunc(self):
return self.a
>>> import inspect
>>> inspect.getmembers(MyClass, lambda a:not(inspect.isroutine(a)))
[('__class__', type),
('__dict__',
<dictproxy {'__dict__': <attribute '__dict__' of 'MyClass' objects>,
'__doc__': None,
'__module__': '__main__',
'__weakref__': <attribute '__weakref__' of 'MyClass' objects>,
'a': '34',
'b': '12',
'myfunc': <function __main__.myfunc>}>),
('__doc__', None),
('__module__', '__main__'),
('__weakref__', <attribute '__weakref__' of 'MyClass' objects>),
('a', '34'),
('b', '12')]
Now, the special methods and attributes get on my nerves- those can be dealt with in a number of ways, the easiest of which is just to filter based on name.
>>> attributes = inspect.getmembers(MyClass, lambda a:not(inspect.isroutine(a)))
>>> [a for a in attributes if not(a[0].startswith('__') and a[0].endswith('__'))]
[('a', '34'), ('b', '12')]
...and the more complicated of which can include special attribute name checks or even metaclasses ;)
Get all attributes of a class in Python
Use vars
for property, value in vars(your_class).iteritems():
print(property, ":", value)
Can I get all attributes that were defined in the __init__ method of a class?
You can do this by looking at the __dict__
attribute or using the vars
function like so:
class A:
def __init__(self):
self.a = "a"
self.b = "b"
print(A().__dict__) # prints {'a': 'a', 'b': 'b'}
print(vars(A())) # also prints {'a': 'a', 'b': 'b'}
Get the list of 'property' class attributes of a class in python
property
s are defined on the class, if you try to access them via an instance, their __get__
is called. So make it a class method instead:
@classmethod
def get_props(cls):
return [x for x in dir(cls)
if isinstance( getattr(cls, x), property) ]
Get all object attributes in Python?
Use the built-in function dir()
.
How to get types of attributes of a class object without initializing it in python
Without initialization local params like param0
and param2
are not evaluated, so Python interpreter has no information about their existence or type.
The only possibility you have is to collect arguments of __init__
method. Using your example structure:
import inspect
params = []
for parent in ExampleParams.mro()[::-1]:
parent_init = inspect.getfullargspec(parent.__init__)
# parent_init.annotations contains annotations if specified in method signature
for param in parent_init.args:
if param == 'self':
continue
params.append(param)
params = ['param1']
in your case.
Print all properties of a Python Class
In this simple case you can use vars()
:
an = Animal()
attrs = vars(an)
# {'kids': 0, 'name': 'Dog', 'color': 'Spotted', 'age': 10, 'legs': 2, 'smell': 'Alot'}
# now dump this in some way or another
print(', '.join("%s: %s" % item for item in attrs.items()))
If you want to store Python objects on the disk you should look at shelve — Python object persistence.
Related Topics
How to Change Index of a for Loop
Pandas Make New Column from String Slice of Another Column
How to Do/Workaround a Conditional Join in Python Pandas
Python: Can Executable Zip Files Include Data Files
Cumsum as a New Column in an Existing Pandas Data
How to Add Multiple Annotations to a Barplot
Python Float - Str - Float Weirdness
How to Print One Character at a Time on One Line
How to Sort a List with Two Keys But One in Reverse Order
What Is the G Object in This Flask Code
Scikit-Learn & Statsmodels - Which R-Squared Is Correct