Home > Software design >  How to get attributes (not methods) of a class in Python
How to get attributes (not methods) of a class in Python

Time:08-05

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).

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

CodePudding user response:

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().

  • Related