如何在python中获取对象的属性类型 [英] How to get type of object's attribute in python

查看:20
本文介绍了如何在python中获取对象的属性类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下课程:

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

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

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.

非常感谢:)

推荐答案

RHP 几乎拥有它.您想要组合 dirtypegetattr 函数.这样的理解应该就是你想要的:

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:] != '__']

这会给你 ['int', 'str'] (因为 myIntmyStr 之前按字母顺序排序).

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

分解:

  1. getattr 在对象上查找属性的名称
  2. type 获取对象的类型
  3. __name__type 上给出类型的字符串名称
  4. dir 列出对象的所有属性(包括 __dunder__ 属性)
  5. comprehension 中的 if 测试过滤掉了 __dunder__ 属性
  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

这篇关于如何在python中获取对象的属性类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆