如何从python中的另一个类中获取内容?

2024-10-05 14:25:46 发布

您现在位置:Python中文网/ 问答频道 /正文

我在MyGame类中的draw函数中创建了两个不同的类OrangesWitches,还有一个MyGame,我需要从Oranges类中获取位置并将其添加到Witches类中的位置。例如,新的女巫位置=橙色的位置-女巫的位置。我该怎么做?你知道吗

class Orange(object):
    def __init__(self, position, image):
        self.image = image
        self.position = (random.randint(350, 500), random.randint(250, 350))  

    def draw(self, surface):
        surface.blit(self.image, self.position)

class Witch(object):
    def __init__(self, position, image):
        self.image = image
        self.position = (random.randint(0, 760), random.randint(0, 0))
        self.position1 = (random.randint(0, 0), random.randint(0, 520))
        self.position2  = (random.randint (0, 760), random.randint(480, 520))
        self.position3 = (random.randint (730, 760), random.randint(0, 520))

    def draw(self, surface):
        surface.blit(self.image, self.position)

class MyGame(object):
    def draw(self):

Tags: imageselfobjectinitdefpositionrandomsurface
1条回答
网友
1楼 · 发布于 2024-10-05 14:25:46

你的代码真的很长,但只要减去橙色和女巫类的位置,下面就足够了。你必须为orange和witch类创建一个对象,只需执行以下操作。我不知道你是否在问别的问题,但从你的问题来看,我只能说这些了。你知道吗

new_orange=Orange(...input parameters...)
new_witch=Witch(...input parameters...)
new_witch.position=new_orange.position-new_witch.position

注意:您有两个位置是tuple,因此我建议您查看map feature并执行以下操作:

new_witch.position=tuple(map(lambda x,y:x-y,new_orange.position,new_witch.position))

这将给你iterable对象,你可以把它转换成tuple,我想把它留给你,作为一个动机去寻找lambda和iterable对象。你知道吗

相关问题 更多 >