Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get attributes (not methods) of a class in Python

How to get attributes (not methods) of a class in Python

Hello everyone!

Basically, I’m looking to retrieve all attributes of a class without having access to self (To create a diagram that includes the attributes).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

For now I don’t have any code, I just have an ‘obj’ variable which contains the class.
I would therefore like to know, how, via "obj" I can retrieve all the attributes including those which are in functions.

Thanking you in advance,
VitriSnake

>Solution :

You can call __dict__ on your class and it will return a dictionary containing all attributes with their values set by the constructor.

class Tree:
    def __init__(self):
        self.trunk_size = 20
        self.leaf_colour = "Orange"

if "__main__" == __name__:
    tree = Tree()
    print(tree.__dict__)

Result: {'trunk_size': 20, 'leaf_colour': 'Orange'}

If you just want the values call tree.__dict__.values() and for your keys or rather attribute variable names do tree.__dict__.keys().

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading