是否可以在 class 之外输入一个 class 变量?

Is it possible to make a class variable my input outside the class?

我使用 fbchat 模块来收听我的消息并将我的回复用作验证码的输入。当我想调用我的 class 变量时,除了最后一行,我什么都想通了。有什么想法吗?

这是我的代码:

from fbchat import Client
from fbchat.models import *
import fbchat
from fbchat import log, Client

# Subclass fbchat.Client and override required methods
class EchoBot(Client):
   def onMessage(self, author_id, message_object, thread_id, thread_type, **kwargs):
       self.markAsDelivered(thread_id, message_object.uid)
       self.markAsRead(thread_id)

       log.info("{} from {} in {}".format(message_object, thread_id, thread_type.name))

       # If you're not the author, echo
       if author_id != self.uid:
           self.send(message_object, thread_id="id", thread_type=ThreadType.USER)

       captchaResponse = str(message_object.text) # This is the text it receive 




client = EchoBot("mail", "password")
client.listen()

captchaInput = driver.find_element_by_xpath("//input[@id='captchaResponse']")
captchaImage = driver.find_element_by_id("captchaTag")
captchaImage.screenshot("captcha/captcha.png")
captchaImage = cv2.imread('captcha/captcha.png')
captchaInput.send_keys(captchaResponse, Keys.ENTER) # This is where I'm stuck

编辑:

所以问题是我需要在我的函数末尾添加这一行,然后才能做任何其他事情。

Client.stopListening(self)

您在 onMessage 的函数范围内声明了 captchaResponse,这意味着它在外部不可用。

在 class 之前声明它,然后使用 global 关键字访问外部 captchaResponse 以从函数内部覆盖它。

captchaResponse = None

class EchoBot(Client):
    def onMessage(self, author_id, message_object, thread_id, thread_type, **kwargs):
        ...
        global captchaResponse 
        captchaResponse = str(message_object.text) # This is the text it receive 

然后应该可以在 captchaInput.send_keys 中使用它。

using global variables in a function

上的相关主题