【问题标题】:Get class object __dict__ without special attributes获取没有特殊属性的类对象__dict__
【发布时间】:2010-12-27 17:52:51
【问题描述】:

为了获取我尝试使用的所有已定义的类属性

TheClass.__dict__

但这也给了我特殊的属性。有没有办法只获取自定义属性,还是我必须自己“清理”字典?

【问题讨论】:

    标签: python oop new-style-class


    【解决方案1】:

    另一种解决方案:

    class _BaseA(object):
        _intern = object.__dict__.keys()
    
    class A(_BaseA):
        myattribute = 1
    
    print filter(lambda x: x not in A._intern+['__module__'], A.__dict__.keys())
    

    我不认为这是非常强大的,可能还有更好的方法。

    这确实解决了一些其他答案指出的一些基本问题:

    • 无需'name convention' 基于过滤
    • 提供您自己的魔术方法实现,例如__len__ 没问题(在A中定义)。

    【讨论】:

    • 整洁!我没有想到以这种方式使用子类。
    【解决方案2】:

    你无法清理__dict__

    AttributeError: attribute '__dict__' of 'type' objects is not writable
    

    你可以信赖naming conventions:

    class A(object):
        def __init__(self, arg):
            self.arg = arg
    
        class_attribute = "01"    
    
    print [ a for a in A.__dict__.keys() 
            if not (a.startswith('__') and a.endswith('__')) ]
    
    # => ['class_attribute']
    

    这可能不可靠,因为您当然可以在课堂上覆盖或实现special/magic methods,如__item____len__

    【讨论】:

      【解决方案3】:

      我不认为有什么简单的,为什么会有?魔法属性和用户定义属性之间没有语言强制的区别。

      如果您有一个以“__”开头的用户定义属性,MYYN 的解决方案将不起作用。但是,它确实建议了一个基于约定的解决方案:如果您想内省自己的类,您可以定义自己的命名约定,并对其进行过滤。

      也许如果您解释需要我们可以找到更好的解决方案。

      【讨论】:

        猜你喜欢
        • 2011-11-21
        • 2019-12-02
        • 1970-01-01
        • 2017-12-20
        • 2017-12-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多