如何(在 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
。
请注意,在 Python 中,“属性”具有非常具体的含义(内置property
类型)。如果您只关心这一点,那么您只需要查找您的子类__dict__
:
val = [p.__get__(c) for k, p in type(c).__dict__.items() if isinstance(p, property)]
如果你想要一些可以在任意属性上工作的东西,那么你所要求的就是不可能的,因为 Python 对象(除了少数例外)是基于 dict 的(与 C++ 或 Java 中的基于结构的)和动态的(任何一块代码可以在每个实例的基础上添加/删除任意属性),因此没有固定模式或给定对象可能拥有或不拥有的属性的类级别定义。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句