【问题标题】:Is putting functions in classes a good practice? [duplicate]将函数放在类中是一种好习惯吗? [复制]
【发布时间】: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


【解决方案1】:

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

如果你想多次使用它,而不仅仅是从 __init__ 中,那么你可以将它声明为私有方法

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

我会等到其他班级想要使用它之前将它放在课堂之外

【讨论】:

    【解决方案2】:

    首先,如果函数在类中,则需要一个 self 参数(但我看到你在 init 中创建了它,所以没关系)

    其次,该函数是否属于矩形?似乎只是生成列表列表的随机函数。在那种情况下,个人意见说两种选择:

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

    【讨论】:

      猜你喜欢
      • 2022-01-20
      • 2019-11-20
      • 1970-01-01
      • 2018-09-26
      • 1970-01-01
      • 2011-08-30
      • 2015-05-16
      • 2014-10-06
      • 1970-01-01
      相关资源
      最近更新 更多