当我创建一个对象时,我将作为参数传递什么?

时间:2014-04-10 21:48:04

标签: python class methods

我在名为“worldmodel.py”的文件中有这个类/函数:

import entities
import pygame
import ordered_list
import actions
import occ_grid
import point

class WorldModel:
   def __init__(self, num_rows, num_cols, background):
      self.background = occ_grid.Grid(num_cols, num_rows, background)
      self.num_rows = num_rows
      self.num_cols = num_cols
      self.occupancy = occ_grid.Grid(num_cols, num_rows, None)
      self.entities = []
      self.action_queue = ordered_list.OrderedList()


def add_entity(world, entity):
   obj = occ_grid.Grid()
   pt = entities.get_position(entity)
   if within_bounds(world, pt):
      old_entity = occ_grid.get_cell(pt)
      if old_entity != None:
         entities.clear_pending_actions(old_entity)
      obj.set_cell(pt, entity)
      world.entities.append(entity)

我在名为“occ_grid.py”的文件中有另一个类/方法:

# define occupancy value
EMPTY = 0
GATHERER = 1
GENERATOR = 2
RESOURCE = 3

class Grid:
   def __init__(self, width, height, occupancy_value):
      self.width = width
      self.height = height
      self.cells = []

      # initialize grid to all specified occupancy value
      for row in range(0, self.height):
         self.cells.append([])
         for col in range(0, self.width):
            self.cells[row].append(occupancy_value)

   def set_cell(self, point, value):
      self.cells[point.y][point.x] = value

如果查看def add_entity正文中的第一行代码,您会看到我创建了一个对象,以便我可以使用set_cell,这是occ_grid.py的方法1}}。我不确定的是作为参数传递给occ_grid.Grid()的内容。任何反馈/想法都表示赞赏!

1 个答案:

答案 0 :(得分:1)

def __init__(self, width, height, occupancy_value),您可以看到需要传递selfwidthheightoccupancy_value

现在,self已经存在,但你需要传递其他3个:

occupancy_value = # Whatever initial value you want all the cells to have
width = # Whatever width you want
height = # Whatever height you want
obj = occ_grid.Grid(width, height, occupancy_value)