从其他函数中取一个变量值?????蟒蛇

时间:2014-03-28 22:30:31

标签: python

任何人都可以帮我这个吗?

我有这两个功能......我只想将值 SP 带到 create_ball_numbers ... 但总是我有一个错误消息...(如下所示)

class have_settings():

    def create_ball_speed(self, speed):
        self.the_ball_speed = speed
        self.sp = 0

        if self.the_ball_speed   == "slow":
            self.sp =  2
        elif self.the_ball_speed == "normal":
            self.sp = 4
        elif self.the_ball_speed == "fast":    
            self.sp =  6

    def create_ball_numbers(self, number):
        self.the_ball_number = number

        if self.the_ball_number in (1,2,3):
            for n in range(self.the_ball_number):

                self.position_x = random.randrange(10,734)
                self.position_y = random.randrange(10,200)

                self.ball_img = games.load_image("ball.jpg")
                self.ball = Bounce(image = self.ball_img,
                                   x = self.position_x,
                                   y = self.position_y,
                                   dx = sp,
                                   dy = -1)
                games.screen.add(self.ball)

错误味精......

NameError: global name 'sp' is not defined

AttributeError: 'Application' object has no attribute 'sp'

1 个答案:

答案 0 :(得分:0)

正如@Benjamin所说,但将所有全局变量放在类定义的顶部也是一种好习惯。例如:

class Foo:

    Bar = 0

    def __init__(self, bar):
        self.Bar = bar

    def doStuff(self):
        for i in xrange(10000):
            print(self.Bar)