简体   繁体   中英

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 , ie height and width .

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.

If property == to attribute , from the doc :

Attribute assignments and deletions update the instance's dictionary, never a class's dictionary.

So even you do self._color = color on a base class, you are assigning that attribute/property to the instance of the B class.

So, at least that you save info tied to the attribute/property for consult latter, I don't think that given how Python works, you will be able to determine to what class the method in which a property was assigned belong to , that is how your question means in Python.

I hope that this helps you to clarify the OOP model of Python.

If you are referring to Python's properties , then the @bruno answer is perfect. I will still leave this answer here because is kind of related to your topic and could be useful for readers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM