【问题标题】:How may I access an attribute of a class from the __init__ of another?如何从另一个类的 __init__ 访问一个类的属性?
【发布时间】:2020-09-17 07:24:33
【问题描述】:

我正在处理 OOP 任务,因为我们刚刚被介绍过。 我们要创建两个类:AnimalDesert 他们为我们指定了这些类必须具有的各种属性和方法

Desert 包含一个Grid 属性,一些Animal 对象应该分布在该属性上。 Animal 对象用'A' 表示,出现在网格上,但也将它们的位置存储在本地,它们的属性为AcrossDown

Animal 类的__init__ 中,我们应该在Grid 上选择一个随机位置来放置动物。这意味着将AcrossDown 属性设置为随机值,同时修改Grid 以在此位置显示'A'

我不确定如何从Animal 对象访问Grid。下面是相关代码,cmets与任务的不同要点有关:

class Animal(Desert):

  # Constructor
  def __init__(self):

    # Generate a pair of random numbers between 0 and 39.
    rand_num1 = randint(0, 39)
    rand_num2 = randint(0, 39)

    # Place an animal at that random position.
    self.Across = rand_num1
    self.Down = rand_num2
    # HERE IS WHERE I WOULD LIKE TO MODIFY THE GRID ATTRIBUTE OF DESERT

    # Initialise the animal's score to 0.
    self.Score = 0
class Desert:

  # Constructor
  def __init__(self):


    # attributes:
    self.Grid = []
    self.StepCounter = 0
    self.AnimalList = []
    self.NumberofAnimals = 0

    # Initialises an empty grid
    self.Grid = [['ロ' * 40] * 40]

    # Creates 5 animal objects which are added to the AnimalList
    for _ in range(5):
      self.AnimalList.append(Animal())

【问题讨论】:

  • 关于你的类层次结构:Animal is-a Desert?这对我来说听起来很奇怪。
  • 但是如果一个Animal 一个Desert,并且你正确地调用了超类__init__实现,那么它就是self.Grid
  • 你的self.Grid = [['ロ' * 40] * 40] 没有做你想做的事。如果你想要一个真正的矩阵,使用这个:self.Grid = [['ロ'] * 40 for _ in range(40)]。如果您使用 * 而不是 range,您将拥有副本,并且更改一个元素将导致总共 40 个更改的元素,因为它们都是对同一对象的引用。

标签: python python-3.x class oop object


【解决方案1】:

您可能需要重新考虑 Animal 和 Desert 之间的关系。如果您查看沙漠的 init,它应该会给您一些指示。沙漠有一个动物列表,这与动物是有关系的。您可以将其解读为,沙漠有动物而不是动物是沙漠。根据这种建模关系,您可以执行类似的操作来访问沙漠的网格。

沙漠可能有一个添加动物的函数,当您添加新动物时,您可以将网格作为参数传递给 Animal 构造函数。像这样的,

 #Animal __init__
 # Constructor
   def __init__(self, grid):
      ...


 # Desert __init__
 ....
 # Creates 5 animal objects which are added to the AnimalList
 for _ in range(5):
   self.AnimalList.append(Animal(self.Grid))

同时移除 Desert for Animal 的继承。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    • 2020-02-18
    • 1970-01-01
    • 1970-01-01
    • 2010-12-04
    • 1970-01-01
    相关资源
    最近更新 更多