如何让这个 class 接受 list/tuple 的整数作为参数?

How do I make this class accept list/tuple of ints as arguments?

我尝试将从输入中获得的变量(即 (x,y,z) 作为整数)成功地转换为元组和列表,但我似乎无法使 Polynomial() 工作和他们在一起。

from tkinter import *

class Polynomial:

    def __init__(self, *coefficients):
        self.coefficients = list(coefficients)

    def __repr__(self):

        return "Polynomial" + str(self.coefficients)

    def __call__(self, x):
        res = 0
        for index, coeff in enumerate(self.coefficients[::-1]):
            res += coeff * x ** index
        return res


def calculateIt():
    mathCoef = E1.get()
    botch = mathCoef
    mytuple = tuple(map(int, botch.split(',')))

    p = Polynomial(mytuple)

    for x in range(-3, 3):
       print(x, p(x))
    L1.configure(text=p)
    print(mathCoef)

window = Tk()
window.title("XImath Client 1.0")
window.configure(bg="black")
window.geometry("500x500")

L1 = Label(window, text="Input")
L1.pack()
E1 = Entry(window, bd=5)
E1.pack()

B1 = Button(window, text="go", command=calculateIt)
B1.pack()

window.mainloop()

问题是我希望 class(Polynomial) 与用户在 mathCoef 中输入的变量一起工作,它最初是一个字符串。我尝试成功地转换为一个元组,但是 class(Polynomial) 期望使用这种语法的整数 - (1, 2, 3)。假设用户输入 1,2,3 - 元组看起来完全像这样 - (1, 2, 3),但是当我尝试将它传递给 Polynomial(mytuple) 时,它 returns:

TypeError: unsupported operand type(s) for +=: 'int' and 'tuple'

如何将元组转换为以逗号分隔的整数?

试试下面的代码。

我相信您可能遗漏的是 p = Polynomial(*coeffs) 行中的 *,它告诉 python 将列表解包为传递给 class 的构造函数的参数.

我还在将多项式添加到标签的行中添加了 repr(p),这将向您显示该多项式的 repr 字符串。

from tkinter import *

class Polynomial:

    def __init__(self, *coefficients):
        self.coefficients = list(coefficients)

    def __repr__(self):

        return "Polynomial" + str(self.coefficients)

    def __call__(self, x):
        res = 0
        for index, coeff in enumerate(self.coefficients[::-1]):
            res += coeff * x ** index
        return res


def calculateIt():
    mathCoef = E1.get()
    coeffs = map(int, mathCoef.split(' '))

    p = Polynomial(*coeffs)

    for x in range(-3, 3):
       print(x, p(x))
    L1.configure(text=repr(p))
    print(mathCoef)

window = Tk()
window.title("XImath Client 1.0")
window.configure(bg="black")
window.geometry("500x500")

L1 = Label(window, text="Input")
L1.pack()
E1 = Entry(window, bd=5)
E1.pack()

B1 = Button(window, text="go", command=calculateIt)
B1.pack()

window.mainloop()