[英]Python : how to call a function in another Class
我被困在https://python4kids.brendanscott.com/2014/12/02/hooking-up-the-sunfish-chess-engine-advanced/上的一些Python脚本:我遵循了Brendan Scott和构建他所描述的Python小脚本,以获取TKinter GUI for sunfish.py,这是一个漂亮的小象棋应用程序。 但是该代码包含一些错误,尽管他的文章和说明非常清楚并且设置正确。
首先,这产生了“ KeyError”错误:
def location_to_algebraic(board_location):
return "%s%s"%(ALGEBRAIC_DICT[7-board_location.j],8-board_location.i)
我只是通过以下方式解决了:
def location_to_algebraic(board_location):
return "%s%s"%(ALGEBRAIC_DICT[math.ceil(7-board_location.j)],math.ceil(8-board_location.i))
说明:用户在棋盘正方形上的某处单击的屏幕上的点似乎给出x,y浮点数,而整数则应为整数,因为它们是字典的索引。 仅仅通过使用math.ceil()进行四舍五入,我们得到了正确的整数,并且它可以按预期工作。 奇怪,看来作者没有测试最终脚本。
但是此脚本中的另一个(简单?)错误我无法解决:
move, score = sunfish.search(pos)
给出此错误: AttributeError:模块“ sunfish”没有属性“ search”
似乎search()函数未正确调用,尽管它确实存在于模块“ sunfish”中:位于其类“ Searcher”中。 所以我尝试通过以下方式修复它:
move, score = sunfish.Searcher.search(pos)
但是然后我又得到一个错误:
TypeError:search()缺少2个必需的位置参数:“ pos”和“ secs”
现在调用了search()函数,但是参数很少! 当我尝试通过以下方法解决此问题时:
move, score = sunfish.Searcher.search(pos, secs=2)
我得到另一个错误:
TypeError:search()缺少1个必需的位置参数:“ pos”
我现在停滞了..这是有关sunfish.Searcher类中的搜索功能,它非常简单:
def search(self, pos, secs):
start = time.time()
for _ in self._search(pos):
if time.time() - start > secs:
break
return self.tp_move.get(pos), self.tp_score.get((pos, self.depth, True)).lower
如何正确调用search()?
Searcher类的初始化是这样的:
class Searcher:
def __init__(self):
self.tp_score = LRUCache(TABLE_SIZE)
self.tp_move = LRUCache(TABLE_SIZE)
self.nodes = 0
sunfish.Searcher.search()函数带有3个参数,第一个变量是self,它引用该类的当前实例。 因此,当您在不创建sunfish.Searcher对象的情况下调用搜索函数时,不会自动提供self变量,self会获得pos的值,secs会获得2的值。
要解决此问题,您需要先创建一个sunfish.Searcher对象,然后通过该对象调用搜索功能。
例:-
Obj = sunfish.Searcher()
Obj.search(pos, secs)
这是一篇清楚说明python中类和对象概念的文章:-https: //www.programiz.com/python-programming/class
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.