มัณฑนากรเธรด [Python]
ฉันกำลังพยายามสร้างโปรแกรมง่ายๆโดยใช้ python socket และ threading library ฉันต้องการทำให้ขั้นตอนต่อไปนี้เป็นอัตโนมัติโดยใช้มัณฑนากร:
t = threading.Thread(target=function, args=(arg1, arg2))
t.start()
โปรแกรมมีโครงสร้างโดยใช้ OOP ดังนั้นฉันจึงกำหนดคลาสย่อยภายในคลาสหลักเพื่อให้มีมัณฑนากรทั้งหมด (ฉันได้อ่านเกี่ยวกับวิธีนี้ในบทความนี้: https://medium.com/@vadimpushtaev/decorator-inside-python-class-1e74d23107f6). ดังนั้นฉันจึงมีสถานการณ์เช่นนี้:
class Server(object):
class Decorators(object):
@classmethod
def threaded_decorator(cls, function):
def inner_function():
function_thread = threading.Thread(target=function)
function_thread.start()
return inner_function
def __init__(self, other_arguments):
# other code
pass
@Decorators.threaded_decorator
def function_to_be_threaded(self):
# other code
pass
แต่เมื่อฉันพยายามเรียกใช้ฉันได้รับข้อผิดพลาดต่อไปนี้: TypeError: function_to_be_threaded() missing one required argument: 'self'. ฉันสงสัยว่าปัญหาอยู่ในส่วนเมื่อฉันเรียกเธรดเธรด (target = function) ซึ่งไม่ผ่านฟังก์ชั่นทั้งหมด self.function_to_be_threaded ดังนั้นถ้าคุณรู้วิธีแก้ไขโปรดบอกฉันได้ไหม?. นอกจากนี้คุณสามารถบอกฉันได้ไหมว่ามีวิธีในการใช้งานมัณฑนากรที่ยอมรับอาร์กิวเมนต์ซึ่งจะส่งผ่านไปยังคลาสเธรดเป็นargs=(arguments_of_the_decorator)?
ขอบคุณมากที่สละเวลาและแก้ตัวภาษาอังกฤษของฉันฉันยังคงฝึกฝนอยู่
คำตอบ
ใช้*argsไวยากรณ์การย้าย arguments.In คำอื่น ๆ ที่ใช้*argsในการเก็บรวบรวมทั้งหมดข้อโต้แย้งตำแหน่งเป็น tuple และย้ายไปเป็นthreading.Threadargs
import threading
import time
class Server(object):
class Decorators(object):
@classmethod
def threaded_decorator(cls, function):
def inner_function(*args):
function_thread = threading.Thread(target=function,args=args)
function_thread.start()
return inner_function
def __init__(self, count,sleep):
self.count = count
self.sleep = sleep
@Decorators.threaded_decorator
def function_to_be_threaded(self,id):
for xx in range(self.count):
time.sleep(self.sleep)
print("{} ==> {}".format(id,xx))
>>> Server(6,1).function_to_be_threaded('a')
>>> Server(2,3).function_to_be_threaded('b')
a ==> 0
a ==> 1
a ==> 2
b ==> 0
a ==> 3
a ==> 4
a ==> 5
b ==> 1
ดูเพิ่มเติมฉันจะส่งอาร์กิวเมนต์จากฟังก์ชันหนึ่งไปยังอีกฟังก์ชันหนึ่งได้อย่างไร