我正在检查属性的实例是否属于某个类型,但在该求值中,它作为属性对象返回,而不是我分配给它的getter。你知道吗
类似问题的其他答案表明,这可能是因为getter使用了一些尚未定义的内容,但据我所知,所有内容都已定义。你知道吗
定义:
class SceneController():
...
def get_scene(self):
if self._current_level_name is not None and self._current_level_name in self._scene_stack:
return self._scene_stack[self._current_level_name]
else:
return None
scene_control = SceneController()
@property
def scene():
return scene_control.get_scene()
使用失败:
# Prints <class 'property'>
print(type(scene))
# This fails
if isinstance(scene, GameScene):
...
这应该起作用:
因为您将
@property
修饰函数与从get_scene
返回的任何对象的实例类型进行比较。我假设self._scene_stack[...]
是GameScene
。你知道吗使用
@property
修饰符时应该小心,因为它是一个特殊的修饰符,因为它提供了额外的属性(只需输入property().getter
)。从本质上讲,装饰师喜欢:基本上是
foo(bar())
,所以我不确定这是否是装饰器的实际用例。你知道吗在python中,
property()
是一个内置函数,它创建并返回一个属性对象。你知道吗此函数的签名为:
property(fget=None, fset=None, fdel=None, doc=None)
。你知道吗fget是getter,fset是setter,fdel是deleter属性。你知道吗
当您编写如下属性时:
@property def foo(): return 'something'
它在内部映射到
foo=property(foo)
。返回值是一个属性对象。你知道吗你可以通过
isinstance(foo, property)
检查它。它会变成真的。你知道吗有关详细信息,请参见property in python。你知道吗
相关问题 更多 >
编程相关推荐