将功能放在课堂上是一种好习惯吗?

时间:2017-02-24 12:32:47

标签: python python-2.7 function class

我不是在问这个具体的例子,而是总的来说。我想知道什么是更好的方法。将该函数保留在类中。例如:

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)

它有什么不同或我不应该担心吗?

2 个答案:

答案 0 :(得分:2)

像你一样把__init__放在里面是没有意义的,因为你可以把代码放在那里......

如果您想要使用它几次而不仅仅是__init__,那么您可以将其声明为私有方法

def _create_walls(self):
    ...
    self.walls = []

我会等到将它放在课外,直到另一堂课想要使用它

答案 1 :(得分:1)

首先,如果函数在类中,你需要一个self参数(但我发现你是在init中创建的,所以没关系)

其次,该功能是否属于任何方式的矩形?似乎只是一个随机函数来生成列表列表。在这种情况下,个人意见说两个选项:

  1. 把它留在外面
  2. 使其成为类
  3. 的静态方法