【发布时间】:2017-07-15 07:00:53
【问题描述】:
我不是在问这个具体的例子,而是在一般情况下。我想知道有什么更好的方法。将函数留在类中。示例:
class Rectangle:
def __init__(self):
room_width = random.randint(MIN_WALL_LEN, MAX_WALL_LEN)
room_height = random.randint(MIN_WALL_LEN, MAX_WALL_LEN)
self.x1 = random.randint(1, WIDTH - rect_width - 1)
self.y1 = random.randint(1, HEIGHT - rect_height - 1)
self.x2 = self.x1 + rect_width
self.y2 = self.y1 + rect_height
# This function is only used for this class
def create_walls(x1, y1, x2, y2):
xs = range(x1, x2)
ys = range(y1, y2)
return [
[(x, y1) for x in xs], # top
[(x1, y) for y in ys], # left
[(x2-1, y) for y in ys], # right
[(x, y2 - 1) for x in xs], # bottom
]
self.walls = create_walls(self.x1, self.y1, self.x2, self.y2)
或者我应该把函数放在外面,所以它只会被定义一次:
def create_walls(x1, y1, x2, y2):
xs = range(x1, x2)
ys = range(y1, y2)
return [
[(x, y1) for x in xs], # top
[(x1, y) for y in ys], # left
[(x2-1, y) for y in ys], # right
[(x, y2 - 1) for x in xs], # bottom
]
class Rectangle:
def __init__(self):
room_width = random.randint(MIN_WALL_LEN, MAX_WALL_LEN)
room_height = random.randint(MIN_WALL_LEN, MAX_WALL_LEN)
self.x1 = random.randint(1, WIDTH - rect_width - 1)
self.y1 = random.randint(1, HEIGHT - rect_height - 1)
self.x2 = self.x1 + rect_width
self.y2 = self.y1 + rect_height
self.walls = create_walls(self.x1, self.y1, self.x2, self.y2)
这有什么不同吗?或者我不应该担心?
【问题讨论】:
-
# This function is only used for this class所以这是这个类的一个方法,应该放在那个类中。 -
不只是在类中,在方法中;它只能在
__init__内访问。 -
你可以做一个静态方法
标签: python python-2.7 function class