简体   繁体   中英

Python Threading “TypeError: _testmethod() takes 2 positional arguments but 12 were given”

I am running a Thread for a class method and am confused by the necessary syntax.

Running code example:

from threading import Thread

class TestClass:
    def _testmethod(self, argument):
        print(argument)

    def __init__(self, arg):
        self.T = Thread(target=self._testmethod, args=(arg,))
        self.T.start()        

C = TestClass("hello world")

This only works as intended, if I put a colon in the argument list: "args=(arg**,**))"

If I leave the colon out like so:

self.T = Thread(target=self._testmethod, args=(arg))

I get a TypeError:

TypeError: _testmethod() takes 2 positional arguments but 12 were given

Could someone please tell me, what's going on?

The args=(arg,) means that the args gets a tuple. The comma in (arg,) tells the Python interpreter, that the parentheses are used to create a single element tuple. If you leave the comma out, then parentheses just enclose the value. Depending on how you pass the argument, it can expand to more than one (that is not wrapped in a tuple).

See the doc 5.3. Tuples and Sequences . It says:

A special problem is the construction of tuples containing 0 or 1 items: the syntax has some extra quirks to accommodate these. Empty tuples are constructed by an empty pair of parentheses; a tuple with one item is constructed by following a value with a comma (it is not sufficient to enclose a single value in parentheses). Ugly, but effective.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM