ООП, Наследование
Есть 3 класса Stone, Seaweed и Place. Но при создании обьекта класса Seaweed пишет что нет атрибута X,Y. Как мне использовать и новые атрибуты init у seaweed, так наследуемые атрибуты place
class Place:
color = (52,152,219)
def __init__(self, x,y):
self.x = x
self.y = y
def aseta(self):
square = pygame.Rect(self.x*10, self.y*10, 10, 10)
pygame.draw.rect(screen, self.color, square)
class Stone(Place):
color = (0,0,0)
class Seaweed(Place):
color = (2,124,2)
def __init__(self, lifePeriod , age, reproductivePeriod ):
self.lifePeriod = lifePeriod;
self.age = age;
self.reproductivePeriod = reproductivePeriod;
def aging(self):
self.age += 1 ;
# def reproduction():
# def dying():
pond = [[ 0 for x in range(width)] for y in range(width)]
for y in range(height):
for x in range(width):
pond[x][y] = Place(x,y);
pond[x][y].aseta()
pygame.display.flip();
num = 0
while num <= stone_count:
x = random.randint(1,width-2)
y = random.randint(1,height-2)
if isinstance(pond[x][y], Place):
pond[x][y] = Stone(x,y)
pond[x][y].aseta();
num += 1
pygame.display.flip();
seawedNum = 0
while seawedNum <= seawed_count:
x = random.randint(1,width-2)
y = random.randint(1,height-2)
if isinstance(pond[x][y], Place):
pond[x][y] = Seaweed(1,1,1)
pond[x][y].aseta();
seawedNum += 1
pygame.display.flip();
Ответы (1 шт):
Автор решения: Roman Konoval
→ Ссылка
В питоне в конструкторе подкласса, Seaweed, например, нужно вызывать конструктор предка. Ведь именно он добавляет в объект атрибуты.
Задача конструктор в принципе проинициализировать объект, так чтоб у него было правильное состояние, удовлетворяющее условиям целостности объекта. Атрибуты это частный случай. И вызов конструктора предка, это обязательно.