[英]How to inherit specific variables from one class to another class?
我正在使用 pygame 模块在 python 中制作游戏,我希望将一个特定变量从一个类继承到另一个类,但不知道如何继承。 我试过 super() 但它没有用,但是,我是新手可能只是意味着我做错了,所以如果它有效,请不要将其视为一种可能性。
我也在下面的代码中列出了我希望继承的变量。
这是我的相关代码如下:
我想继承的类:
class player():
def __init__(self, x, y, width, height, walkCount):
self.x = x
self.y = y
self.width = width
self.height = height
self.vel = 15
self.lastDirection = "right" or "left" or "up" or "down" #<--- variable I want to inherit
self.walkCount = walkCount
def drawCharacter(self, window):
dest = (self.x, self.y)
if self.walkCount + 1 >= 30:
self.walkCount = 0
if self.lastDirection == "left":
window.blit(protagL[0], dest)
elif self.lastDirection == "right":
window.blit(protagR[0], dest)
elif self.lastDirection == "up":
window.blit(protagU[0], dest)
elif self.lastDirection == "down":
window.blit(protagD[0], dest)
我想接收继承的类:
class projectile(player):
def __init__(self, x, y, direction, travelCount):
self.x = x
self.y = y
self.direction = direction
self.vel = 20 * direction
self.travelCount = travelCount
def drawBullet(self, window):
dest = (self.x, self.y)
if self.travelCount + 1 >= 15:
self.walkCount = 0
if lastDirection == "right" or "left": # <--- I Want to call lastDirection variable here
if self.travelCount < 15:
window.blit(bulletsP[self.travelCount//3], dest) #dest)
self.travelCount += 1
self.x += self.vel
任何帮助将不胜感激,谢谢。
您必须调用基类的构造函数。 参见super()
:
class projectile(player):
def __init__(self, x, y, direction, travelCount):
super().__init__(x, y, 10, 10, travelCount)
# [...]
请注意,在您的示例中,宽度和高度的参数不清楚,因此我示例性地使用了 (10, 10)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.