我并不是在询问这个具体的例子,而是总体上。我想知道做什么是更好的方法。将该功能留在课堂上。例如:把功能放在课堂上是一种很好的做法吗?
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)
这有什么区别或者我不应该担心吗?
检查[staticmethod装饰器](https://docs.python.org/2/library/functions.html#staticmethod) 。 – fredtantini
'#这个函数只用于这个类'所以这是这个类的一个方法,应该放在那个类中。 – MKesper
这不仅仅是在课堂上,它是在方法中;它只在* __init__中可访问。 – jonrsharpe