Python - 可以在线程中调用相同的 class 两次(或更多次)吗?

Python - can call same class twice(or more) in thread?

我不是很明白class中python的逻辑,但无法在网上回答。 我创建了一个 class 来生成人员信息:

class person:  
    def fristnameGen(gender):
        ...
    def emailGen(firstname,surname): 
        ...

我创建了一个机器人来这样称呼它:

from person import *
class bots:
    def __init__(self):        
        self.person = person()
    def createDB(self):
        print(self.person.name)
        #do something...

最后我用带线程的按钮调用它

from bots import *
import threading
class Panel:
    def __init__(self):
        self.top = tk.Tk()
        self.bot = bots()
        self.buildUI()

    def foo(self):
        self.bot.createDB(self.stringPhone.get())

    def threadTheAction(func, *args):
        t = threading.Thread(target=func, args=args) 
        t.setDaemon(True) 
        t.start()

    def buildUI(self):
        Button = tk.Button(self.top, text ="Start", command = lambda :self.threadTheAction(self.foo))

我收到这个错误:

TypeError: 'Panel' object is not callable

不过,我直接调用它,它的工作

        Button = tk.Button(self.top, text ="Start", command = lambda :self.foo())

如何修复错误? ... 2. 此外,我尝试创建 p1 = person()p2= person() 并打印它。发现p1p2是同一个人,我更喜欢每新一个class有一个新的。如何使用 classes 生成 "new person"?

谢谢

您似乎对 Python 中的面向对象编程有很多困惑。您的一些方法有 self 个参数,有些没有,似乎是随机的。这就是您当前错误的根源。

Panel class 中的 threadTheAction 方法将 Panel 实例作为第一个参数传入,但在方法(因为你省略了 self)。您作为参数传递的实际函数被捕获在变量参数 *args 中。当线程尝试调用它失败时,您会得到一个异常。在 func 之前添加 self 将解决眼前的问题:

def threadTheAction(self, func, *args):

我怀疑如果您的代码更进一步,您会 运行 使用参数列表中没有 self 的其他方法出现其他错误。例如,您在 person 中展示的方法中的 none 可能会正常工作。

至于你的第二个问题,你没有展示足够的 person 来了解发生了什么,但你可能以某种方式错误地使用了实例变量。由于方法中没有 self 参数,这几乎是不可避免的(因为您分配给 self.whatever 以在当前实例上设置 whatever 属性)。如果您需要帮助解决这个问题,我建议您问一个单独的问题(当每个问题都是独立的时,Stack Overflow 最好)并提供 person class.[=27= 的完整代码]