gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:11:06 24 4
gpt4 key购买 nike

我收到错误“类型错误:'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

关于python - 调用属性 getter、setter、deleter - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22182748/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com