【发布时间】:2016-07-13 22:18:26
【问题描述】:
请考虑以下 python 示例:
In [3]: class test(object):
...: attribute='3'
...: def __init__(self):
...: self.other='4'
...:
In [4]: b=test()
In [5]: b.attribute
Out[5]: '3'
In [6]: b.__dict__
Out[6]: {'other': '4'}
为什么__dict__ 只显示"other" 属性而不显示"atribute"?
我如何获得包含所有类的属性和值的字典?也就是说,我如何得到这个?
{'other': '4', 'attribute': '3'}
我的意思是使用__dict__ 或其他一些简单的方法。
PS:与this question 相关,但无法从那里获得字典。
PS2:我不是在找test.__dict__或者b.__class__.__dict__,我是在找可以当做的东西
In [3]: class test(object):
...: attribute='3'
...: def __init__(self):
...: self.other='4'
...: def _print_atr(self):
...: # This should print exactly {'other': '4', 'attribute': '3'}
...: print(self.__all_atr__)
In [4]: b=test()
In [5]: b.attribute
Out[5]: '3'
In [6]: b.__dict__
Out[6]: {'other': '4'}
干杯
【问题讨论】:
-
你能详细说明你所说的 PS2 是什么意思吗?为什么您假设的
__all_atr__不包括__init__和_print_atr,但它确实 包括attribute? -
@mgilson 是的,抱歉,如果不清楚,这正是它会做的。它会打印出我的例外示例:
{'other': '4', 'attribute': '3'}. -
但是为什么?排除某些事物而不排除其他事物的规则是什么?
-
@mgilson 这个想法是将
b的属性和b的类属性都视为b的属性,同时仍然保持python默认的“排除”属性以一个下划线。但也许这是一种愚蠢的开始方式。你认为我应该删除这个问题吗? -
不,我认为您不必删除该问题。如果您只想过滤“dunder”属性/方法,您可以轻松地从我的回答中过滤字典:
d = {k: v for k, v in d.items() if not (k.startswith('__') and k.endswith('__')}。但我想也值得问为什么你想这样做。最终目标是什么?
标签: python class attributes