singwong
singwong

Reputation: 55

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

I don't very understand the classes logic in python but cannot answer on web. I have create a class to generate person info:

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

i create a bot to call it like this:

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

finally i call it by a button with thread

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))

I get this error:

TypeError: 'Panel' object is not callable

However, i call it directly, its work

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

How to fix the error? ... 2. Moreover, i tried create p1 = person() and p2= person() and print it. Found p1 and p2 is a same person, i prefer each new a class have a new one. How to generate "new person" using classes?

Thank you

Upvotes: 0

Views: 1145

Answers (1)

Blckknght
Blckknght

Reputation: 104712

You seem to have a lot of confusion about Object Oriented Programming in Python. Some of your methods have self parameters and some do not, seemingly at random. That's the source of your current error.

The threadTheAction method in your Panel class is getting the Panel instance passed in as its first argument, but that's named func in the method (since you omitted self). The real function you're passing as an argument gets caught in the variable argument *args. When the thread tries unsuccessfully to call it, you get an exception. Adding self before func would fix the immediate problem:

def threadTheAction(self, func, *args):

I suspect if your code got further along, you'd run into other errors with other methods without self in their parameter lists. For instance, none of the methods you've shown in person are likely to work correctly.

As for your second question, you haven't shown enough of person to know what's happening, but you're probably doing instance variables wrong somehow. With no self parameter in the methods, that's almost inevitable (since you assign to self.whatever to set a whatever attribute on the current instance). If you need help squaring that away, I suggest you ask a separate question (Stack Overflow is best when each question is self-contained) and provide the full code for your person class.

Upvotes: 2

Related Questions