获取没有特殊属性的类对象 __dict__
为了获取所有定义的类属性,我尝试使用,
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
另一个解决方案:
我认为这不是非常强大,可能仍然有更好的方法。
这确实解决了其他一些答案指出的一些基本问题:
'name convention'
的过滤__len__
没问题(在A中定义)。Another solution:
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:
'name convention'
based-filtering__len__
is no problem (define in A).您无法清理
__dict__
:您可以依赖 命名约定:
这可能不可靠,因为您当然可以覆盖或实现 特殊/魔术方法,例如类中的
__item__
或__len__
。You can't clean the
__dict__
:You could rely on naming conventions:
This may not be reliable, since you can of course overwrite or implement special/magic methods like
__item__
or__len__
in your class.我不认为有什么简单的事情,为什么会有呢?魔法属性和用户定义属性之间没有语言强制的差异。
如果您有以“__”开头的用户定义属性,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.