简体   繁体   English

获取自身所有属性的字典,而不包括子类属性

[英]Get a dict of all properties of self without including child class properties

Say I have the following two classes: 说我有以下两节课:

class PlayerState:
    def __init__(self):
        self.someStateProp = 10

    # get the state of this class only as a dict
    def getState(self):
        return {name: attr for name, attr in self.__dict__.items()
                if not name.startswith("__")
                and not callable(attr)
                and not type(attr) is staticmethod}

class Player(PlayerState):
    def __init__(self):
        super().__init__()
        self.someNonStateProp = 'foo'

player = Player()
print(player.getState())
# someNonStateProp should not be shown
>> {'someStateProp': 10, 'someNonStateProp': 'foo'}

The method PlayerState.getState as it stands is able to return a dict containing all attributes of itself, excluding constructors and methods. 方法PlayerState.getState可以返回一个dict ,该dict包含自身的所有属性,但不包括构造函数和方法。 I want to expand on it and make it also only return the direct properties of PlayerState , and not Player . 我想对其进行扩展,使其也仅返回PlayerState的直接属性, PlayerState返回Player的直接属性。

Edit: Using self.__class__.__dict__.items() instead of self.__dict__.items() just gives me all the methods of Player . 编辑:使用self.__class__.__dict__.items()代替self.__dict__.items()只是给了我Player所有方法。

You provide no way to really differentiate between state and non-state attributes. 您无法提供真正区分状态和非状态属性的方法。 If the object is mutable and has a mutable dict, there is really no way to determine who set the value for a particular attribute. 如果对象是可变的且具有可变的dict,则实际上无法确定谁为特定属性设置值。 There will be cases where children will want to add to the state. 在某些情况下,孩子会希望添加到该州。 If the state is something special, keep it as a separate dictionary instead of filtering every time: 如果状态是特殊的,请将其保留为单独的字典,而不是每次都进行过滤:

class PlayerState:
    def __init__(self):
        self.state = {}
        self.state['someProp'] = 10

    # get the state of this class only as a dict
    def getState(self):
        return self.state

class Player(PlayerState):
    def __init__(self):
        super().__init__()
        self.someNonStateProp = 'foo'
        self.state['otherProp'] = 'bar'

If it bothers you that you can't access state elements through normal dot access, add some properties to your class: 如果困扰您,您无法通过普通的点访问来访问状态元素,请向您的类添加一些属性:

@property
def someStateProp(self):
    return self.state['someProp']

Alternatively, hard-code a list of the names you want. 或者,对所需的名称列表进行硬编码。

class PlayerState:
    states = ['someStateProp']

    def __init__(self):
        self.someStateProp = 10

    # get the state of this class only as a dict
    def getState(self):
        return {name: getattr(self, name) for name in self.names}

class Player(PlayerState):
    names = PlayerState.names + ['otherStateProp']

    def __init__(self):
        super().__init__()
        self.someNonStateProp = 'foo'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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