如何在python中获取对象的属性类型

max*_*ern 2 python python-2.7

假设我有以下课程:

class myClass():
    def __init__(self, number):
        self.myStr = "bla"
        self.myInt = number * 3
Run Code Online (Sandbox Code Playgroud)

我如何获得属性类型?我的意思是我想得到以下列表:['str','int']?

我也希望它适用于派生类。

非常感谢 :)

wmo*_*ell 6

RHP 几乎拥有它。你要的结合dirtypegetattr功能。这样的理解应该是你想要的:

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

这会给你['int', 'str'](因为myInt之前myStr按 alpha 顺序排序)。

分解它:

  1. getattr 在对象上查找属性的名称
  2. type 获取对象的类型
  3. __name__在 a 上type给出类型的字符串名称
  4. dir列出对象的所有属性(包括__dunder__属性)
  5. if理解中的测试过滤掉__dunder__属性