Python:如何修复我的代码以便追加将参数添加到列表中?

标签 python python-3.x list append

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

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

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

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

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: Appending a value to a list outside the class, function with append also outside the class, but function is called within a class

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

最佳答案

您需要处理的一些问题。首先在类外部分配 f=True 不会更改内部的值,因此,如果您实例化该类,它只会抛出 UnboundLocalError 提示 f 未初始化。您可以通过实例化该类来自己尝试

fc = firstclass()

如果没有实例化,您就无法希望它为您提供所需的值。由于函数 Secondclass 的打印语句不包含在方法中,因此它打印零,因此它打印该类声明的值 sum(prices)。该值来自价格的原始声明值,即 []。至少这就是您在问题中所展示的方式。我不确定您是否打算缩进打印语句,这意味着它是二等的一部分。但是,如果您没有缩进,您将得到与未实例化第一类相同的结果。

要纠正此问题,请参见下文。此代码将按照您的预期输出 70。

prices = []

class firstclass():
    def __init__(self):
        my_function()

def my_function():
    prices.append(70)

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

print('before instantiation', sum(prices))
fc = firstclass()
print('after instantiation', sum(prices))

fc 现在是一个 firstclass 类型的对象,并且 __init__ 方法已调用 my_function 将值 70 append 到 prices.

关于Python:如何修复我的代码以便追加将参数添加到列表中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57015545/

相关文章:

python - 使用 sqlalchemy 在 sqlite 数据库中保存 numpy 整数

Python 3 正则表达式 $ 但不是字符串中的 $$

Python-PPTX : Data Label Positions not working for Doughnut Chart

python - 如何在 Python Flask 中创建带有可选参数的 SQL 查询?

python - 如何在 Mac 上使用 PyPy?

python - 如何在 Python 和 Flask 上返回列表?

python - 如何从函数中更改全局变量?

list - 如何将带有 NULL 的列表扩展到某个长度?

R 根据匹配的嵌套列表名称对嵌套列表元素应用函数

php - 组合框未更新