说我有以下两个课程:
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'}
方法PlayerState.getState
可以返回一个dict
,其中包含其自身的所有属性,但不包括构造函数和方法。我想对其进行扩展,使其也仅返回PlayerState
的直接属性,而不返回Player
的直接属性。
编辑:使用self.__class__.__dict__.items()
代替self.__dict__.items()
只是给了我Player
的所有方法。
答案 0 :(得分:2)
您无法提供真正区分状态和非状态属性的方法。如果对象是可变的且具有可变的dict,则实际上无法确定谁为特定属性设置值。在某些情况下,孩子会希望添加到该州。如果状态很特殊,请将其保留为单独的字典,而不是每次都进行过滤:
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'
如果让您感到困扰的是您无法通过普通的点访问来访问状态元素,请向您的类中添加一些属性:
@property
def someStateProp(self):
return self.state['someProp']
或者,对所需的名称列表进行硬编码。
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'