Python 把函数放在课堂上是一种很好的做法吗?
我不是问这个具体的例子,而是问一般情况。我不知道有什么更好的方法做这件事。将函数留在类中。例如:Python 把函数放在课堂上是一种很好的做法吗?,python,python-2.7,function,class,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.randin
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)
它有什么区别吗?或者我不应该担心它?首先,如果函数在类中,您需要一个
self
参数(但是我看到您是在init中创建的,所以不用担心)
第二,该函数是否以任何方式属于矩形?似乎只是一个生成列表的随机函数。在这种情况下,个人意见认为有两种选择:
首先,如果函数在类中,您将需要一个
self
参数(但我看到您是在init中创建的,所以不用担心)
第二,该函数是否以任何方式属于矩形?似乎只是一个生成列表的随机函数。在这种情况下,个人意见认为有两种选择:
像您那样放入_uinit__;是毫无意义的,因为您可以将代码放在那里 如果您想多次使用它,而不仅仅是从_uinit__;使用它,那么您可以将它声明为私有方法
def _create_walls(self):
...
self.walls = []
我会等着把它放在类外,直到另一个类想使用它像你那样把它放在类内是没有意义的,因为你可以把代码放在那里 如果您想多次使用它,而不仅仅是从_uinit__;使用它,那么您可以将它声明为私有方法
def _create_walls(self):
...
self.walls = []
我会等待将它放在类外,直到另一个类想要使用它为止。
#这个函数只用于这个类
,所以这是这个类的一个方法,应该放在那个类中。这不仅在类中,它在方法中;它只能在\uuuu init\uuuu
中访问。您可以创建一个StictCheck的staticmethod。\35;此函数仅用于此类
,因此这是此类的一个方法,应该放在该类中。不仅在类中,它在方法中;它只能在\uuuu init\uuuu
中访问。您可以对它创建一个静态方法