pythonpython-3.xoopinheritanceproperties

How to get values of all properties (except inherited ones) that belong to specific class in Python 3


How (in Python 3) to get values of all properties that belong to specific class. I need ONLY those values (properties) that defined in specific class without inherited ones.

Here is some example:

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

and here is a code for fetching all values (including inherited):

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}]

Now, I just want to retrieve values of properties defined ONLY in class B, i.e. height and width.


Solution

  • Note that in Python "property" has a very specific meaning (the builtin property type). If you're only concerned about this then you just have to lookup your child class's __dict__:

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

    If you want something that works on any arbitrary attribute then what you ask for is just not possible, since Python objects (with a few exceptions) are dict-based (vs struct-based like in C++ or Java) and dynamic (any piece of code can add / remove arbitrary attributes on a per-instance basis) so there's no fix schema nor class-level definition of what attributes a given object may or not possess.