如何访问之前在另一个类中定义的类中的变量?

时间:2019-10-21 14:46:29

标签: python

我正在尝试制作一个python库: 其中有一个类(游戏),它是一个定义变量(显示)的函数 然后在main中有另一个类(char),我想访问char中的display 我该怎么办?

过去,我尝试过:self.display,global display和game.display

class game():
    def __init__(self, disp, width, height):
        self.display = disp # VARIABLE I WANT TO ACCESS
        self.height = height
        self.width = width

    class sprite():
        def __init__(self, size, position, image):
            self.image = image
            self.size = size
            self.rect = self.image.get_rect()
            self.rect.x = position[0]
            self.rect.y = position[1]
            self.x = position[0]
            self.y = position[1]
            self.collisionDirection = 5
            self.hasCollided = False
            self.mask = pygame.mask.from_surface(self.image)
            self.velocity = 0

        def render(self):
            self.rect.x = self.x
            self.rect.y = self.y
            self.mask = pygame.mask.from_surface(self.image)
            display.blit(self.image, (self.x, self.y)) # WHERE I WANT TO ACCESS IT

我不断收到AttributeError我该怎么办?

3 个答案:

答案 0 :(得分:1)

您可以将Game实例传递给另一个类。例如

# instantiate the game
g = game()
# create an instance of char
c = char(game)

假设char()的__init__看起来像这样:

class char():
    def __init__(self, game):
        # save a reference to the game object as an attribute
        self.game = game
        # now you can access the game's attributes
        print(self.game.display)

答案 1 :(得分:0)

下面的示例是人为设计的,不太可能采用您设计笔/纸的方式,但是它表明可以通过几种不同的方式来完成您的要求。

class Pen:
    def __init__(self, thickness, color):
        self.thickness = thickness
        self.color = color


class Paper:
    def __init__(self, pen: Pen):
        self.pen = pen

    def draw(self):
        pen_color = self.pen.color
        return pen_color

    def draw2(self, pen: Pen):
        pen_color = pen.color
        return pen_color


red_pin = Pen(2, 'Red')
blue_pin = Pen(1, 'Blue')

paper = Paper(red_pin)
print(paper.draw())              # prints Red
print(paper.draw2(blue_pin))     # prints Blue

答案 2 :(得分:0)

我知道了:

class game():
    def __init__(self, disp, width, height):
        global display
        display = disp

    class char():
        def render():
            display.blit(...........)