【问题标题】:Assinging to a variable赋值给变量
【发布时间】:2020-06-28 17:37:16
【问题描述】:
class main_window:

   def __init__(self, question):
      self.question = question

   def question_func(self):
      return '{}'.format(self.question)

q1 = main_window('In general, my problem is related to:')

main_window.question_func(q1)

如何将 ma​​in_window.question_func(q1) 分配给我可以调用的变量?

【问题讨论】:

  • question_func 返回一个字符串,你打算在这里“调用”什么?
  • 是否需要面向对象的方法?函数式编程似乎是要走的路。
  • 您的 q1 是该类的一个实例,可能是您想传递一个字符串而不是 main_window 本身的实例。假设您要传递一个字符串,您可以执行类似 call_back = main_window.question_func 的操作,将 arg 传递给它类似 call_back(q1)

标签: python class variables


【解决方案1】:

也许你正在寻找这样的东西:

class main_window:

   def __init__(self, question):
      self.question = question

   def question_func(self):
      return '{}'.format(self.question)

q1 = main_window('In general, my problem is related to:')
variable = q1.question_func()
print(variable)

输出:

In general, my problem is related to:

【讨论】:

  • 正是我的意思谢谢,你能解释一下它背后的逻辑吗?我不明白它为什么起作用
  • 您创建了一个main_window 对象q1 并将一些文本分配给它的属性question。然后在q1 上调用函数question_func 并将结果(恰好是question 的值)分配给variable
【解决方案2】:

我不明白你在做什么“main_window.question_func(q1)”。也许你想创建一个静态/类方法??

我认为您可能正在尝试做这样的事情:

class main_window:

   def __init__(self, question):
      self.question = question

   def question_func(self):
      def function_toBe_called():
           return '{}'.format(self.question)

      # question_func returns a function that 
      # returns a string, not a string
      return function_toBe_called

然后你可以这样做:

q1 = main_window('In general, my problem is related to:')

variable_youCan_Call = main_window.question_func()
variable_youCan_Call()

【讨论】:

    猜你喜欢
    • 2021-12-04
    • 2020-07-31
    • 2014-04-30
    • 1970-01-01
    • 2017-08-04
    • 2020-06-26
    • 2021-12-31
    • 2017-09-13
    • 2023-03-13
    相关资源
    最近更新 更多