【问题标题】:Listing Class Attributes and Their Types in Python在 Python 中列出类属性及其类型
【发布时间】:2014-05-16 23:52:04
【问题描述】:

myClass 属性之一与 QListWidget 的拖放事件不兼容。得到这个 AssertionError:

assert id(obj) not in self.memo

我需要跟踪/确定哪个 myClass 属性对 AssertionError 负责,然后在其实例作为 listItem 数据分配给 QListWidget 之前将其删除(稍后在 listItem 被拖动时导致 AssertingError)。

myClass 中有 100 多个 attrs。而且我找不到过滤显然不对 AssertionError 负责的属性的方法。

print dir(myClassInstance)

只打印属性的名称,而不是它们的类型。

同样的无用信息来自

attributes = [attr for attr in dir(myClassInstance) if not attr.startswith('__')]

理想情况下,我想查看 myClass 属性的名称及其类型:它是方法,那是一个字符串.. 那是另一个类的实例等等。

【问题讨论】:

    标签: python


    【解决方案1】:

    考虑使用inspect.getmembers()

    >>> import inspect
    >>> from datetime import datetime
    >>> now = datetime.now()
    >>> inspect.getmembers(now)
    [('__add__', <method-wrapper '__add__' of datetime.datetime object at 0x105754ee0>),
     ...
    ('weekday', <built-in method weekday of datetime.datetime object at 0x105754ee0>), ('year', 2014)]
    

    您还可以传递 predicate 参数,这将有助于过滤掉列表,例如见:

    【讨论】:

    • 感谢您的解决方案!虽然.getmembers() 的输出量很大。而且它似乎不喜欢嵌套类实例,因为如果遇到它,它似乎会循环到无穷大。
    猜你喜欢
    • 2021-06-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-17
    • 2021-12-28
    • 2017-12-09
    • 1970-01-01
    相关资源
    最近更新 更多