如何获取Python3中属于特定类的所有属性(继承属性除外)的值



如何(在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中定义的属性的值,即heightwidth

请注意,在Python中,"属性"有一个非常特殊的含义(内置的property类型(。如果你只关心这一点,那么你只需要查找你孩子班的__dict__:

val = [p.__get__(c) for k, p in type(c).__dict__.items() if isinstance(p, property)]

如果你想要对任意属性有效的东西,那么你所要求的是不可能的,由于Python对象(除了少数例外(是基于dict的(与C++或Java中的基于struct的相比(和动态的(任何代码都可以在每个实例的基础上添加/删除任意属性(,因此既没有固定的模式,也没有类级定义给定对象可能拥有或不拥有什么属性。

最新更新