简体   繁体   English

参数将值传递给我在 python/Pygame 中的类

[英]Parameter Passing values into my Class in python/Pygame

I have a class in Python that will be for the spawning of NPC's in a small space.我有一个 Python 课程,用于在小空间中生成 NPC。 I want to pass the information (such as the location for their image/sprite, their co-ordinates where they'll spawn, etc.) into the class:我想将信息(例如它们的图像/精灵的位置、它们将产生的坐标等)传递到类中:

class NPC(object):
        def __init__(self, img, x, y):
                self.image = pygame.image.load(img).convert_alpha()
                self.x = x
                self.y = y

I want the values img, x and y to be passed in but I cannot think of a suitable method of doing so, as the init function for some reason cannot be called.我希望传入 img、x 和 y 值,但我想不出合适的方法,因为由于某种原因无法调用init函数。

I feel that the solution is staring me right in the face but I don't know how to get to it.我觉得解决方案正盯着我看,但我不知道如何解决。

Not sure why you say that the init cannot be called?不知道为什么你说 init 不能被调用? To run the built in function init you just write:要运行内置函数init,您只需编写:

joe = NPC(joe_image, joe_x, joe_y)

If joe already exists and you want to respawn him, just copy init as another function:如果 joe 已经存在并且您想重生他,只需将 init 复制为另一个函数:

def respawn(self,(self, x, y):
            self.x = x
            self.y = y

and call:并调用:

joe.respawn(joe_x, joe_y)

[I'm assuming you don't need to change his image here] [我假设你不需要在这里改变他的形象]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM