[英]python: how to get all members of an array except for ones that match a condition
[英]How to get values of all properties (except inherited ones) that belong to specific class in Python 3
如何(在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中的基於struct的相比)和動態的(基於代碼可以在每個實例的基礎上添加/刪除任意屬性),因此對於給定對象可能具有或不具有什么屬性,沒有固定的架構或類級別的定義。
如果屬性==為attribute ,則來自doc :
屬性分配和刪除將更新實例的字典,而不會更新類的字典。
因此,即使您在基類上執行self._color = color
,您self._color = color
將該屬性/屬性分配給B類的實例。
因此,至少您保存了與屬性/屬性相關的信息以供以后參考,我認為,鑒於Python的工作原理,您將無法確定分配屬性的方法屬於哪個類 ,即是您的問題在Python中的含義。
我希望這可以幫助您闡明Python的OOP模型。
如果您指的是Python的屬性 ,那么@bruno答案是完美的。 我仍然在這里留下這個答案,因為這與您的主題有關,可能對讀者有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.