Python:如何修复我的代码,以便追加将参数添加到列表中? [英] Python: How do I fix my code so that the append will add the argument to the list?

查看:17
本文介绍了Python:如何修复我的代码,以便追加将参数添加到列表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 python 非常陌生,我一直在尝试执行此代码,其中我使用 tkinter 按钮命令运行一个函数,它可以工作但 append() 没有执行,这意味着它不会附加到列表中.

I am very new to python and I've been trying to do this code where i use a tkinter button command to run a function, it works but the append() is not executing, meaning it does not append to the list.

列表和包含append的函数在类外,然后通过使用tkinter按钮命令在类内进行分类

The list and the function containing the append is outside the class and is then classed within a class through the use of tkinter button command

我已经尝试将函数放入类中,它可以工作,但附加不会再次添加到列表中.

I've tried putting the function inside the class, it works but the append is not adding into the list again.

这是我编写的代码,与真实代码有些相似

This is the code I've made that is somewhat similar to real one

prices = []

f = True
class firstclass():
    def __init__(self):
        while f == True:
            my_function()
            f = False

def my_function():
    prices.append(70)


class secondclass():

    def __init__(self):
        pass

    print(sum(prices))

真实代码示例在此链接中,请考虑到这一点python:附加一个值到类外的列表,附加的函数也在类外,但函数在类内调用

the sample of real code is in this link, please take this into consideration as well python: Appending a value to a list outside the class, function with append also outside the class, but function is called within a class

我预计它会打印附加值 70,但它仍然打印 0

I expected that it would print the appended value which is 70, but it still printed 0

推荐答案

发生这种情况有两个原因.

There are two reasons this is happening.

  1. 您从未调用 firstclass 来实际初始化构造函数.
  2. 您正在尝试将 False 分配给变量 f不属于类的范围.如果你仍然分配它,它被认为是本地的.而此刻的口译员检测到您分配了它,while 循环没有任何本地f 的引用,因为您没有在构造函数下定义它.有关详细信息,请参阅答案.
  1. You never called firstclass to actually initialize the constructor.
  2. You are trying to assign False to the variable f which does not belong to the scope of the class. If you still assign it, it's considered local. And at the moment the interpreter detects that you assigned it, the while loop does not have any local reference of f since you did not define it under the constructor. See this answer for more details.

这是完整的代码:

prices = []
class firstclass():
    f = True
    def __init__(self):
        while self.f:
            my_function()
            self.f = False
def my_function():
  prices.append(70)


class secondclass():
    def __init__(self):
        pass

firstclass()
print(sum(prices))

这篇关于Python:如何修复我的代码,以便追加将参数添加到列表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆