簡體   English   中英

Python:如何在另一個類中調用函數

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM