How to get type of object's attribute in pytho

2020-07-25 08:18发布

问题:

assume I have the following class:

class myClass():
    def __init__(self, number):
        self.myStr = "bla"
        self.myInt = number * 3

how do I get the the attributes types? I mean I want to get the following list: ['str','int']?

I also want it to work on derived classes.

Thanks a lot :)

回答1:

RHP almost has it. You want to combine the dir, type, and getattr functions. A comprehension like this should be what you want:

o = myClass(1)
[type(getattr(o, name)).__name__ for name in dir(o) if name[:2] != '__' and name[-2:] != '__']

This will give you ['int', 'str'] (because myInt sorts before myStr in alpha-order).

Breaking it down:

  1. getattr looks up the name of an attribute on an object
  2. type gets the type of an object
  3. __name__ on a type gives the string name of the type
  4. dir lists all attributes on an object (including __dunder__ attributes)
  5. the if test in the comprehension filters out the __dunder__ attributes


回答2:

Use the type() function. You can even use it to print out the variable type like this:

print(type(variable_name))