Skip to main content
 首页 » 编程设计

python之调用属性 getter、setter、deleter之Python

2025年05月04日15lyj

我收到错误“类型错误:'locationTile' 在尝试调用其 fdel() 方法时不是可调用对象。代码:

class GamePlayLocationTiles(object): 
    """The stuff needed for game play""" 
    _locationTiles = [] 
 
    def locationTiles(): 
        doc = "property locationTiles's doc string" 
        def fget(self): 
            return self._locationTiles[0] 
        def fset(self, value): 
            self._locationTiles = value[0] 
        def fdel(self): 
            del self._locationTiles[0] 
        return locals()  # credit: David Niergarth 
    locationTiles = property(**locationTiles()) 
 
    def __init__(self): 
        self.fill_location_tiles_list() 

不同的模块:

import game_play_model 
 
class GamePlayController: 
    """perform operations on the game_play_model""" 
 
    def __init__(self): 
        self.the_game_location_tiles = game_play_model.GamePlayLocationTiles() 
        self.shuffle_location_tiles() 
 
 
    def shuffle_location_tiles(self): 
        self.the_game_location_tiles.locationTiles().fdel() //this line causes the error 
 
def main(): 
    the_game_play_controller = GamePlayController() 
 
if __name__ == '__main__': 
    main() 

只是尝试删除它作为使用 getter、setter、deleter 访问私有(private)变量的测试。

请您参考如下方法:

def shuffle_location_tiles(self): 
    del self.the_game_location_tiles.locationTiles 

不应直接调用fdel 函数。当实例尝试删除该属性时,它将为您调用。

例如,

class Foo(object): 
    def x(): 
        def fget(self): 
            """I'm the 'x' property.""" 
            return self._x 
 
        def fset(self, value): 
            self._x = value 
 
        def fdel(self): 
            print('deleting x') 
            del self._x 
        return locals() 
    x = property(**x()) 
 
    def __init__(self): 
        self._x = None 
 
 
c = Foo() 
del c.x 
# deleting x 

self.the_game_location_tiles.locationTiles() 引发错误

"Type error: 'locationTile' is not a callable 

因为 self.the_game_location_tiles.locationTiles 调用 fget 并返回值 self._locationTiles[0]。该值恰好不可调用。

您可以使用 GamePlayLocationTiles.locationTiles 访问属性本身,并调用 fdel

GamePlayLocationTiles.locationTiles.fdel(self.the_game_location_tiles) 

但是当你可以只使用语句时没有理由这样做

del self.the_game_location_tiles.locationTiles