【问题标题】:How to get values of all properties (except inherited ones) that belong to specific class in Python 3如何获取属于 Python 3 中特定类的所有属性(继承的属性除外)的值
【发布时间】: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 中定义的属性值,即heightwidth

【问题讨论】:

  • 循环遍历 B.__dict__vars(B) 在这种情况下,dir() 是递归的。
  • 实际上想要达到什么目标;为什么你认为你需要这个?

标签: python python-3.x oop inheritance properties


【解决方案1】:

请注意,在 Python 中,“属性”具有非常特定的含义(内置 property 类型)。如果你只关心这个,那么你只需要查找你的子类的__dict__

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

如果您想要对任意属性起作用的东西,那么您所要求的就是不可能的,因为 Python 对象(除了少数例外)是基于 dict 的(相对于 C++ 或 Java 中的基于结构的)和动态的(任何一段代码都可以在每个实例的基础上添加/删除任意属性),因此对于给定对象可能拥有或不拥有哪些属性没有固定架构或类级别定义。

【讨论】:

  • 这就是 OP 特别要求的 ;)
  • @AnttiHaapala 这就是我从 OP 的代码 sn-p 中理解的,但是在 OO 中“属性”具有更一般的含义,所以我想我最好提一下。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-10
  • 2012-06-09
  • 2022-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多