python怎么访问实例变量_Python:如何从另一个类访问实例变量?

概念上:我想从其他类访问某个类中定义的实例变量

我的例子:我想从我的外星类访问在人类类中定义的self.x实例变量

为什么?:我正在制作一个太空入侵者游戏,里面有2艘宇宙飞船(人类类),外星人正在“雨点般落下”,目标是躲避那些外星人。我将有2个对象对应于2艘飞船。在我的外星类中有一个部分,它检测它是否在两个宇宙飞船的碰撞区域(第二个代码块)。所以基本上,因为'self.x'变量是每艘飞船的一个实例变量,如果我可以在我的外星人类中访问它,那么任何一个外星物体都可以检测到两个宇宙飞船的碰撞(因为self.x代表每艘宇宙飞船的x坐标)。在class Human:

y = display_height * 0.8

width = 120

x_change = 0

def __init__(self, image, initpos, left, right):

self.image = image

self.x = display_width * initpos

self.left = left

self.right = right

def run(self):

global gameExit

for event in pygame.event.get():

if event.type == pygame.QUIT:

gameExit = True

if event.type == pygame.KEYDOWN:

if event.key == self.left:

if self.x > 0:

self.x_change = -8

else:

self.x_change = 0

elif event.key == self.right:

if self.x < display_width - Human.width:

self.x_change = 8

else:

self.x_change = 0

if event.type == pygame.KEYUP:

if event.key == self.left or event.key == self.right:

self.x_change = 0

gameDisplay.blit(self.image, (self.x, Human.y))

self.x += self.x_change

human1 = Human(pygame.image.load('human.png'), 0.5, pygame.K_LEFT, pygame.K_RIGHT)

human2 = Human(pygame.image.load('human2.png'), 0.3, pygame.K_a, pygame.K_d)

class Alien:

height = 120

width = 80

x = random.randrange(width, (display_width - width))

y = -100

def __init__(self, image, speed, hp):

self.image = image

self.speed = speed

self.hp = hp

def run(self):

gameDisplay.blit(self.image, (self.x, self.y))

self.y += self.speed

def checkpos(self):

global points

if self.y > display_height:

self.y = 0 - Alien.height

self.x = random.randrange(Alien.width, display_width - Alien.width)

points += 1so this is where the issue starts basically Human.y works fine since y is a class variable, it remains static as the human ship only changes in the horizontal axis. But x is an instance variable for Human: and I can't make it a class variable because ill need to do a multiplayer mode where there will be 2 ships so each human object has to be controlled separately. So I need to somehow access the instant variable self.x from the Human: class in my following if statement which is in the alien class

^{pr2}$

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值