gpt4 book ai didi

python - 当在另一个函数(self)中声明函数(self)时,“self”丢失了一些东西

转载 作者:太空宇宙 更新时间:2023-11-03 15:00:59 26 4
gpt4 key购买 nike

请观察以下代码(Win10上的python 3.6,PyCharm),函数thread0(self)作为线程成功启动,但是 thread1(self)似乎与thread0(self)不同已设置。 self.thread0很好,但是self.thread1不是。 selfself.thread1没有thread1在其类函数中,但它具有 __init__() 中的所有内容。事实上,在 PyCharm 中,参数 self def thread1(self): 行中甚至没有突出显示。我的理解是像foo(self)这样的语法会将 foo() 添加为 self 所指向的类的成员.

既然说到这里,我无法解释为什么启动thread0的try-catch block 中的代码也失败了,也许这与线程的具体语法要求有关?

我有一种感觉,嵌套使用self这样可能不推荐。但在我的实际代码中,我确实需要在新进程中声明线程,而不是 main() ,以便这些线程可以共享该进程的同一个 python 记录器。

import threading
import multiprocessing
from time import sleep


class exe0(multiprocessing.Process):
def __init__(self):
super().__init__()
self.aaa = 111

# working syntax for thread0
t = threading.Thread(
target=self.thread0,
daemon=1,
)
t.start()

try:
# NOT working syntax
t = threading.Thread(
target=thread0,
args=(self,),
daemon=1,
)
t.start()
sleep(1)
except Exception as e:
print(e)

def thread0(self):
print(type(self))

def run(self):

# working syntax for thread1
def thread1(self):
print(type(self))
print(self.aaa)

t = threading.Thread(
target=thread1,
args=(self,),
daemon=1,
)
t.start()
sleep(1)

try:
# NOT working syntax
t = threading.Thread(
target=self.thread1,
daemon=1,
)
t.start()
sleep(1)
except Exception as e:
print(e)


if __name__ == '__main__':
multiprocessing.freeze_support()
e = exe0()
e.daemon = 1
e.start()
sleep(2)

# output:
'''
<class '__main__.exe0'>
name 'thread0' is not defined
<class '__mp_main__.exe0'>
111
'exe0' object has no attribute 'thread1'
'''

最佳答案

你忘了明白 self 只是一个变量名,代表的是另一回事,为了让你的代码正常工作,你只需为你的变量选择另一个名字,看看:

Important edit

您忘记将名为t4的线程中的方法作为目标

import threading
import multiprocessing
from time import sleep


class exe0(multiprocessing.Process):
def __init__(self):
super().__init__()
self.aaa = 111

t1 = threading.Thread(
target=self.thread0,
daemon=1,
)
t1.start()

try:
t2 = threading.Thread(
target=self.thread0, #here I removed the other parameter
daemon=1,
)
t2.start()
sleep(1)
except Exception as e:
print(e)

def thread0(self):
print(type(self))


def run(self):
def thread1(s): #here you can see the name doesn't matter
print(type(s)) #here you can see the name doesn't matter
print(s.aaa)


t3 = threading.Thread(
target=thread1(self),
daemon=1,
)
t3.start()
sleep(1)

try:
t4 = threading.Thread(
target=thread1(self), #here there is no need of the parameter
daemon=1,
)
t4.start()
sleep(1)
except Exception as e:
print(e)


multiprocessing.freeze_support()
e = exe0()
e.daemon = 1
e.start()
sleep(2)

现在您获得了 6 个输出,例如:

<class 'exe0'>
<class 'exe0'>
<class 'exe0'>
111
<class 'exe0'>
111

关于python - 当在另一个函数(self)中声明函数(self)时,“self”丢失了一些东西,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45113912/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com