3

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

Ivan Kolesnikov
  • 1,787
  • 1
  • 29
  • 45
max stern
  • 55
  • 1
  • 1
  • 5

2 Answers2

11

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
wmorrell
  • 4,988
  • 4
  • 27
  • 37
  • is there any easy way to check if a certain class has attribute of some derived object? – max stern Aug 15 '17 at 05:50
  • `dir` lists _all_ attributes on an object; if the object's class inherits from another class, an instance of that object will have all the attributes on both. – wmorrell Aug 15 '17 at 05:51
  • I have a tiny problem with your solution: in some cases I get inside the list - "'instancemethod'". – max stern Aug 15 '17 at 06:18
  • That would be from an object having methods as attributes. Methods are members of an object, too. You can filter these out by splitting up the list comprehension, and removing items if the result of `type` has a `__call__` attribute. – wmorrell Aug 15 '17 at 06:24
  • sorry, but I maybe wasn't clear enough. I want to know the type of objects that show up as 'instance' and 'instancemethod'. I guess these are the attributes that were inherited. that was my first problem. – max stern Aug 15 '17 at 06:35
  • Those _are_ the types of objects. `instancemethod` is the type of a method attribute, it is a function with `self` bound to the first argument. – wmorrell Aug 15 '17 at 06:52
  • I think I should reopen another question – max stern Aug 15 '17 at 06:58
0

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

print(type(variable_name))
Rahul P
  • 2,493
  • 2
  • 17
  • 31
  • 1
    Suppose you find out this information. How do you expect it to *help you*? You should explain more about what you are *really trying to do*. – Karl Knechtel Aug 15 '17 at 10:59