Python 如何使用继承,我缺少什么?
我是python新手,我正在尝试实践一些基本概念。 我正试图建立一个太阳和地球围绕它旋转的基本模型。 我有两个类,一个类继承自另一个类,但“父”类似乎使用了“子”类的函数。。。 当太阳静止不动时,会发生什么?它会随着地球自转>< 我做错了什么Python 如何使用继承,我缺少什么?,python,inheritance,pygame,overriding,Python,Inheritance,Pygame,Overriding,我是python新手,我正在尝试实践一些基本概念。 我正试图建立一个太阳和地球围绕它旋转的基本模型。 我有两个类,一个类继承自另一个类,但“父”类似乎使用了“子”类的函数。。。 当太阳静止不动时,会发生什么?它会随着地球自转>< 我做错了什么 from math import cos, sin pygame.init() win_size = width, height = 800, 800 center_screen = [center_x, center_y] = [int(width/2
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=位置
然后实例变量self.location
存储对列表location
的引用,但它不创建列表的副本。因此,在alt结束时,对象引用相同的数据列表。注意,在python中,变量名是对对象的引用。数据包含在对象中。当您进行赋值时,引用被赋值,两个变量引用同一个对象 复制列表以解决问题:
self.location=location[:]
[:]
包装了一个较浅的副本。我不理解第一个问题:父类调用的唯一函数是pygame.draw.circle
;我看不出它在哪里使用了Planet
中的任何东西。位置问题是因为您为所有对象指定了一个主位置。为了确保这一点,在更改时打印出该变量并使用它。请看这个可爱的博客寻求帮助。