【发布时间】:2018-02-07 18:12:36
【问题描述】:
如何(在 Python 3 中)获取属于特定类的所有属性的值。我只需要那些在特定类中定义而没有继承的值(属性)。
这里有一些例子:
class A(object):
def __init__(self, color):
self._color = color
@property
def color(self):
return self._color
class B(A):
def __init__(self, color, height, width):
super().__init__(color)
self._height = height
self._width = width
@property
def height(self):
return self._height
@property
def width(self):
return self._width
这是获取所有值(包括继承)的代码:
b_inst = B('red', 10, 20)
val = [{p: b_inst.__getattribute__(p)} for p in dir(B)
if isinstance(getattr(B, p), property)]
print(val)
>> [{'color': 'red'}, {'height': 10}, {'width': 20}]
现在,我只想检索仅在class B 中定义的属性值,即height 和width。
【问题讨论】:
-
循环遍历
B.__dict__或vars(B)在这种情况下,dir()是递归的。 -
你实际上想要达到什么目标;为什么你认为你需要这个?
标签: python python-3.x oop inheritance properties