我尝试构建一个名为"Point"的类,表示3d坐标(x,y,z(。
class Point(object):
def __init__(self):
a = 3
self.data = [[[bool(False) for x in xrange(a)] for y in xrange(a)] for z in xrange(a)]
def __call__(self, x, y, z):
return 'call :'+self.data[x][y][z]'
我可以轻松访问一个点:
p = Point()
print p(1 ,1, 1) # output : False`
但是,我无法为这一点分配值!
p(1, 1, 0) = True # SyntaxError: can't assign to function call
知道吗?
好吧,如果你写这个,你会得到以下错误:
SyntaxError: can't assign to function call
请注意,这是一个SyntaxError
,这意味着Python甚至懒得尝试评估它。它说:这不在Python语法中,所以它不应该以这种方式工作。
接近您要求的内容的是覆盖__setitem__
函数,以便您可以使用p[1,1,0]
进行分配(请注意,这些是方括号(。喜欢:
class Point(object):
def __init__(self):
a = 3
self.data = [[[bool(False) for x in xrange(a)] for y in xrange(a)] for z in xrange(a)]
def __setitem__(self,idx,val):
i,j,k = idx
self.data[i][j][k] = val
def __call__(self, x, y, z):
return 'call :'+str(self.data[x][y][z])
现在它的工作原理是:
>>> p = Point()
>>> p(1,1,0)
'call :False'
>>> p[1,1,0] = True # note the square brackets
>>> p(1,1,0)
'call :True'