gpt4 book ai didi

python - 在 Python 中访问其他类的函数

转载 作者:行者123 更新时间:2023-11-28 20:27:55 24 4
gpt4 key购买 nike

我是 Python 的新手,很抱歉这个明显的问题。我希望 Computer_paddle 类能够调用 Ball 的函数 y_position(),并获取返回值。但它似乎并没有这样做,告诉我:

"global name 'ball' is not defined". 

要在另一个函数中调用一个函数,我需要做些什么特别的事情吗?

class Ball(games.Sprite):
""" A ball that bounces off walls and paddles. """
image = games.load_image("ball.png")

def __init__(self, game, x, y):
""" Initialise ball sprite. """
super(Ball, self).__init__(image = Ball.image,
x = x, y = y,
dx = -3, dy = 0)

def update(self):
"""Check if ball has hit paddle or wall, and then bounce that ball. """
super(Ball, self).update()

# check if ball overlaps paddles
if self.overlapping_sprites:
self.dx = -self.dx
self.dy += random.randint(-1, 1)

# check if ball hits a wall
if self.top < 0 or self.bottom > games.screen.height:
self.dy = -self.dy
if self.left < 0 or self.right > games.screen.width:
self.dx = -self.dx

def y_position(self):
return self.y

class Paddle(games.Sprite):
""" A paddle that can only partly leave the screen. """
image = games.load_image("paddle.png")

def __init__(self, game, x, y):
""" Initialise paddle sprite."""
super(Paddle, self).__init__(image = Paddle.image, x = x, y = y)

def update(self):
""" Prevent sprite from completely leaving the screen. """
if self.top < -33:
self.top = -33

if self.bottom > games.screen.height + 33:
self.bottom = games.screen.height + 33

class Human_paddle(Paddle):
""" A paddle controlled by the player. """

def update(self):
""" Move paddle to mouse position. """
super(Human_paddle, self).update()

self.y = games.mouse.y

class Computer_paddle(Paddle):
""" A paddle controlled by the computer. """
MAX_SPEED = 1

def update(self):
""" Move paddle towards ball's position on Y-axis. """
super(Computer_paddle, self).update()

ball_y = ball.y_position()

if ball_y > self.y:
self.y += MAX_SPEED
if ball_y < self.y:
self.y -= MAX_SPEED

最佳答案

不,但是您需要有一个对象的引用才能访问它的方法。因为您从不将 ball 绑定(bind)到任何东西,所以没有对象可以调用方法。您是想在全局级别创建 ball 作为 Ball 的实例吗?

关于python - 在 Python 中访问其他类的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7137437/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com