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 :)
Use the type() function. You can even use it to print out the variable type like this:
RHP almost has it. You want to combine the
dir
,type
, andgetattr
functions. A comprehension like this should be what you want:This will give you
['int', 'str']
(becausemyInt
sorts beforemyStr
in alpha-order).Breaking it down:
getattr
looks up the name of an attribute on an objecttype
gets the type of an object__name__
on atype
gives the string name of the typedir
lists all attributes on an object (including__dunder__
attributes)if
test in the comprehension filters out the__dunder__
attributes