我有一個名爲'Movable Piece'的類。當然,我希望這個班級的每個實例都可以移動。爲此,我認爲另一個名爲'運動'的課程會很好,並且可以重複使用以防我需要其他東西移動。此外,我很喜歡my_piece.move.up
在代碼中的外觀。爲Python中的實例動態創建方法
當我意識到需要動態地嘗試設置由Piece實例化的Movements類的實例的方法時,問題就出現了,因爲移動該部分的功能也可以由用戶定義。我怎樣才能做到這一點?我認爲該代碼將闡明我想要做的事情。
class MovablePiece(Piece):
class Movements:
def __init__(self, piece, movement_functions=None):
if movement_functions is None:
self.__default_movements(piece)
else:
self.__set_movements(movement_functions)
def __default_movements(self, piece):
def up(): return piece.move(piece.surroundings[Direction.UP])
def right(): return piece.move(piece.surroundings[Direction.RIGHT])
def down(): return piece.move(piece.surroundings[Direction.DOWN])
def left(): return piece.move(piece.surroundings[Direction.LEFT])
self.__set_movements([up, right, down, left])
def __set_movements(self, movement_functions):
for movement_function in movement_functions:
setattr(self, movement_function.__name__, movement_function)
def __init__(self, letter, name, movements=None, walkable=False):
Piece.__init__(self, letter, name, walkable)
self.move = MovablePiece.Movements()
這當然是行不通的:SETATTR正試圖設置功能屬性,我不認爲做多大意義,但你得到它的要點。
這是錯誤,當我嘗試做my_piece.move.right
:
Traceback (most recent call last):
File "main.py", line 45, in <module>
screen.show()
File "/home/joaquin/Documents/escape/ludema/screen.py", line 12, in show
function()
File "main.py", line 35, in control_bruma
mappings[action]()
File "/home/joaquin/Documents/escape/ludema/pieces.py", line 78, in right
def right(): return piece.move(piece.surroundings[Direction.RIGHT])
TypeError: 'Movements' object is not callable
類似的問題,如果我強迫的方法是staticmethods(因爲他們實際上並不需要「自我」):
Traceback (most recent call last):
File "main.py", line 45, in <module>
screen.show()
File "/home/joaquin/Documents/escape/ludema/screen.py", line 12, in show
function()
File "main.py", line 35, in control_bruma
mappings[action]()
TypeError: 'staticmethod' object is not callable
'setattr()'應該可以正常工作。問題可能是函數沒有被定義爲接受「自我」第一個參數,所以它們不是合適的方法。 – martineau
它沒有。我會附上回溯給出的錯誤。 – joaquinlpereyra
@martineau當我嘗試使它們成爲靜態方法時,我添加了回溯函數,它不容易獲取參數:) – joaquinlpereyra