[抱歉,我是Python新手.虽然这似乎是一个非常基本的问题,但我在询问这些观众之前做了我的尽职调查,试图避免真正愚蠢的问题.
我试图弄清楚从函数返回l值的正确习惯用法.假设我有一个64个对象的容器,我希望能够返回对这些对象的引用.
class ChessBoard:
def __init__(self):
self.squares = [None for x in range(64)]
square( row, col ):
return self.squares(row*8+col) <---- I'd like this to be l-value
Run Code Online (Sandbox Code Playgroud)
然后,从课外我想:
board = ChessBoard()
board.square(0,0) = Piece( Shapes.ROOK, Colors.White ) <-- I'm getting an error here
board.square(0,1) = Piece( Shapes.BISHOP, Colors.White )
... etc.
Run Code Online (Sandbox Code Playgroud)
所以,我希望函数'at'返回一个左值(类似于C++中的引用),但是我找不到类似于语言中的引用或指针的东西.如果我在包含一块的每个方块中存储一个列表,我可以做类似的事情:board.square(0,0)[0] = Piece - 但它看起来很疯狂(或者可能不是 - 正如我所说,我'我是语言的新手.
您将如何处理此数据结构?
在Python中,一切都是参考.唯一的问题是它None是不可变的,因此您不能使用返回的引用来更改值.
您也无法覆盖赋值运算符,因此您不会得到这种特殊的行为.但是,一个好的,非常灵活的解决方案是覆盖实现类的订阅operator()的方法__setitem__和__getitem__方法[]:
class ChessBoard(object):
def __init__(self):
self.squares = [None] * 64
def __setitem__(self, key, value):
row, col = key
self.squares[row*8 + col] = value
def __getitem__(self, key):
row, col = key
return self.squares[row*8 + col]
Run Code Online (Sandbox Code Playgroud)
用法:
>>> c = ChessBoard()
>>> c[1,2] = 5
>>> c[1,2]
5
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2018 次 |
| 最近记录: |