如何使用继承,我错过了什么?

How to use inheritance, what am i missing?

我是 python 的新手,我正在尝试练习一些基本概念。 我正在尝试建立一个太阳和地球围绕它旋转的基本模型。 我有 2 个 classes,1 个 class 继承自另一个,但似乎 "Father" class 正在使用 "son" class... 会发生什么,而不是太阳静止不动,它与地球一起旋转>< 我做错了什么?

from math import cos, sin
pygame.init()

win_size = width, height = 800, 800
center_screen = [center_x, center_y] = [int(width/2), int(height/2)]

window = pygame.display.set_mode(win_size)
pygame.display.set_caption("Testing")


class Star(object):
    def __init__(self, location, size, color):
        self.location = location
        self.size = size
        self.color = color

    def draw(self, win):
        pygame.draw.circle(win, self.color, self.location, self.size, 0)


class Planet(Star):
    def __init__(self, location, size, color, speed, r):
        Star.__init__(self, location, size, color)
        self.alpha = 0
        self.r = r
        self.speed = speed

    def draw(self, win):
        self.set_pos()
        pygame.draw.circle(win, self.color, self.location, self.size, 0)

    def set_pos(self):
        self.location[0] = int(self.r*cos(self.alpha)) + center_x
        self.location[1] = int(self.r*sin(self.alpha)) + center_y
        self.alpha += 1


sun = Star(center_screen, 20, (255, 255, 0))
earth = Planet(center_screen, 10, (0, 0, 255), 2, 100)


def redraw_game_window():
    window.fill((0, 0, 0))
    sun.draw(window)
    earth.draw(window)
    pygame.display.update()


run = True
while run:
    pygame.time.delay(200)

    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    keys = pygame.key.get_pressed()
    if keys[pygame.K_ESCAPE]:
        run = False

    redraw_game_window()

pygame.quit()

当你这样做时

self.location = location

然后实例变量 self.location 存储对列表 location 的引用,但它不会创建列表的副本。所以最后 alt 对象引用相同的数据列表。
请注意,在 python 中,变量名是对对象的引用。数据包含在对象中。当您进行赋值时,将分配引用并且两个变量都引用同一个对象。

复制列表解决问题:

self.location = location[:]

[:] 创建一个 list.

的浅拷贝