【发布时间】:2015-12-20 14:09:08
【问题描述】:
(最终)编辑:好的,所以我是个十足的笨蛋。我的识别是为了让我在__init__ 之后的所有方法实际上都在我的__init__ 中。这是语法错误。
我想知道是否可以使用方法(类的成员)初始化变量。基本上,它看起来像这样:
class Tile:
def __init__(self, x, y, tile_type):
self._x = x
self._y = y
self._tile_type = tile_type
self._color = my_method()
(further in class)
def my_method(self):
#my definition
目前,它给了我一个错误:
UnboundLocalError: local variable 'my_method' referenced before assignment
问题是我用这样的理解列表声明了一个二维数组
[[Tile(i,j,0) for i in range(Y_SIZE)] for j in range(X_SIZE)]
因此,如果可能的话,我想避免第二个嵌套循环将my_method() 的返回值放入类属性_color。
谢谢!
编辑:按照要求,我会更具体:我想将my_method() 返回的值分配给_color。对缩进感到抱歉,my_method(self) 实际上在 Tile 类中。
对于那些真正想要类的完整代码的人:
class Tile:
def __init__(self, x, y, tile_type):
self._x = x
self._y = y
self._tile_type = tile_type
self._color = self.set_color_variation()
def _get_x(self):
return self._x
def _set_x(self, x):
self._x = x
x = property(_get_x, _set_x)
def _get_y(self):
return self._y
def _set_y(self, y):
self._y = y
y = property(_get_y, _set_y)
def _get_color(self):
return self._color
def _set_color(self, color):
self._color = color
color = property(_get_color, _set_color)
def _get_tile_type(self):
return self._tile_type
def _set_tile_type(self,tile_type):
self._tile_type = tile_type
tile_type = property(_get_tile_type, _set_tile_type)
def set_color_variation(self):
_color = make_color(TILE_COLOR[_tile_type], TILE_COLOR_VARIATION[_tile_type])
它目前给我的错误信息:
AttributeError: 'Tile' object has no attribute 'set_color_variation'
如果我写
self._color = set_color_variation()
它给了我:
UnboundLocalError: local variable 'set_color_variation' referenced before assignment
【问题讨论】:
-
正如目前所写的那样,
my_method实际上并不在Tile中,尽管您无论如何都不会通过self访问它;请给minimal reproducible example 提供完整的错误回溯以澄清问题。 -
您希望
self._color成为调用my_method()的结果,还是希望它包含对方法本身的引用? -
您可以像这样
def __init__(self, x, y, tile_type, my method)在构造函数中将 my_method 作为参数传递 -
正如我在刚刚进行的编辑中所说,我希望
self._color包含my_method()的返回值。很抱歉这个模棱两可的声明。
标签: python class methods attributes initialization