【发布时间】:2020-09-17 07:24:33
【问题描述】:
我正在处理 OOP 任务,因为我们刚刚被介绍过。
我们要创建两个类:Animal 和 Desert
他们为我们指定了这些类必须具有的各种属性和方法
Desert 包含一个Grid 属性,一些Animal 对象应该分布在该属性上。
Animal 对象用'A' 表示,出现在网格上,但也将它们的位置存储在本地,它们的属性为Across 和Down。
在Animal 类的__init__ 中,我们应该在Grid 上选择一个随机位置来放置动物。这意味着将Across 和Down 属性设置为随机值,同时修改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())
【问题讨论】:
-
关于你的类层次结构:
Animalis-aDesert?这对我来说听起来很奇怪。 -
但是如果一个
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