【问题标题】:Why can I not alter the value of shape_amount?为什么我不能改变 shape_amount 的值?
【发布时间】:2022-01-23 18:34:02
【问题描述】:

我正在努力寻找一种解决方案,在不同的类中将 shape_amount 的值加 1,然后返回该值以进行比较。

这是第一个比较 shape_amount 值的类。

class BEGIN_DRAWING:
    def begin_draw(run, shape_opt, color_value, color):
        global shape_amount
        shape_amount = 0
        i = True
        while i == True:
            color = color_value(color)
            run.movement(shape_amount, color)
            print(shape_amount)
            if shape_amount == shape_opt:
                i = False
        run.movement(shape_amount, color)

我打印 shape_amount 来检查它的值,但输出 0

class DRAWING_CURVED:
    def fill(shape_amount, color):
        rand_int = randint(0, 20)
        if rand_int == 0:
            end_fill()
            fillcolor(color)
            begin_fill()
            shape_amount += 1
            return shape_amount 

这应该在每次填充形状时将 shape_amount 的值加 1,但它似乎没有这样做。

【问题讨论】:

  • 只是一个建议,但python中类的约定是标题大小写,如BeginDrewing
  • 会改的谢谢
  • 在您的第二个代码块中,shape_amount 是一个局部变量;它与同名的全局变量完全无关(即使它们碰巧具有相同的值)。分配给局部变量在函数之外没有任何影响。
  • 哦,没想到不能访问全局

标签: python python-3.x


【解决方案1】:

据我所知,您将shape_amount 全局变量作为参数传递给函数。该参数不会被视为全局变量,而是普通参数。

下面突出显示了这一点,它为我打印:
2
1
2

def test():
    global x
    x = 1
    val = increment(x)
    print(val)
    print(x)
    increment_two()
    print(x)

def increment(x):
    return x + 1

def increment_two():
    global x
    x += 1

if __name__ == "__main__":
    test()

【讨论】:

  • 非常感谢问题已经解决了
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-14
  • 1970-01-01
  • 2021-09-27
  • 1970-01-01
相关资源
最近更新 更多