获取没有特殊属性的类对象 __dict__

发布于 2024-08-15 15:50:27 字数 119 浏览 7 评论 0原文

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

TheClass.__dict__

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

For getting all the defined class attributes I try to go with

TheClass.__dict__

but that also gives me the special attributes. Is there a way to get only the self-defined attributes or do I have to "clean" the dict myself?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

穿越时光隧道 2024-08-22 15:50:27

另一个解决方案:

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中定义)。

Another solution:

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())

I don't think this is terribly robust and there might still be a better way.

This does adress some of the basic issues some of the other answers pointed at:

  • No need for 'name convention' based-filtering
  • Providing your own implementation of magic methods, e.g. __len__ is no problem (define in A).
梦冥 2024-08-22 15:50:27

您无法清理 __dict__

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

您可以依赖 命名约定

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']

这可能不可靠,因为您当然可以覆盖或实现 特殊/魔术方法,例如类中的__item____len__

You can't clean the __dict__:

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

You could rely on 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']

This may not be reliable, since you can of course overwrite or implement special/magic methods like __item__ or __len__ in your class.

北方的韩爷 2024-08-22 15:50:27

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

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

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

I don't think there's anything simple, and why would there be? There's no language-enforced difference between magic and user-defined attributes.

MYYN's solution won't work if you have a user-defined attribute starting with '__'. However, it does suggest a solution based on conventions: if you want to introspect your own classes, you can define your own naming convention, and filter on that.

Perhaps if you explain the need we can find a better solution.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文