2017-02-24 71 views
0

我并不是在询问这个具体的例子,而是总体上。我想知道做什么是更好的方法。将该功能留在课堂上。例如:把功能放在课堂上是一种很好的做法吗?

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) 

这有什么区别或者我不应该担心吗?

+1

检查[staticmethod装饰器](https://docs.python.org/2/library/functions.html#staticmethod) 。 – fredtantini

+2

'#这个函数只用于这个类'所以这是这个类的一个方法,应该放在那个类中。 – MKesper

+1

这不仅仅是在课堂上,它是在方法中;它只在* __init__中可访问。 – jonrsharpe

回答

1

首先,你需要一个self参数,如果函数是在类(但我看到你在init做到了,所以请不要介意)

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

  1. 离开它外面
  2. 让它类
2

把里面__init__像你这样是没有意义的,因为你可以把静态方法代码中有...

如果你想使用它几次,不仅从__init__那么你可以声明为private方法

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

我会等到将它放到课程之外,直到另一个课程想要使用它

相关问题