属性返回作为属性对象,而不是它的 getter,在 isinstance 评估中

2024-09-27 23:18:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在检查属性的实例是否属于某个类型,但在该求值中,它作为属性对象返回,而不是我分配给它的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):
    ...

Tags: nameself内容getreturnif属性定义
2条回答

这应该起作用:

if isinstance(scene(), GameScene)
    ...

因为您将@property修饰函数与从get_scene返回的任何对象的实例类型进行比较。我假设self._scene_stack[...]GameScene。你知道吗

使用@property修饰符时应该小心,因为它是一个特殊的修饰符,因为它提供了额外的属性(只需输入property().getter)。从本质上讲,装饰师喜欢:

@foo
def bar():
    ...

基本上是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。你知道吗

相关问题 更多 >

    热门问题