【问题标题】:How to execute a class method from another class with the method passed a parameter in Python如何使用在Python中传递参数的方法从另一个类执行类方法
【发布时间】:2018-04-10 20:08:07
【问题描述】:

我是学习python的初学者.. 我正在寻求解决 OOP 问题的帮助

我的主程序简化如下:

class abc(Frame):
     def _init_(self,  master)
           Frame.__init__(self)     
           self.B1 = Mybutton(self.master, self.cmd)
     def cmd(self):
           print("hello world")

在主程序中,我在另一个文件中导入Mybutton类,简化如下:

class Mybutton():
     def _init_(self, parent, command):
           self.command = command

     def A_ramdom_fcn(self): 
           ...
           self.command()  ------------------>> here I want to execute the command
                                                                       in class abc, not in class Mybutton.

如何从另一个类中执行作为实例方法传递的方法,您可能会问为什么不在类 abc 中执行它,但我有事件附加到按钮按下,它需要做一个迂回来实现这一点。 .

【问题讨论】:

  • 这是一个错字,在主程序中是正确的..

标签: python oop methods callback


【解决方案1】:

理论上,你正在尝试的是可能的,你可以将对象方法捕获到变量中并稍后调用它(python 3):

class Window:

    def __init__(self):
        self.my_button = Mybutton(self.cmd)

    def cmd(self):
        print("hello world")


class Mybutton:

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

    def a_ramdom_fcn(self):
        self.command.__call__()


win = Window()
win.my_button.a_ramdom_fcn()

我假设您正在尝试创建通用的 Button 类,当它被单击时不知道该怎么做,并且您想将实际逻辑放入您的 Window 类中。

这是有道理的,但最好将逻辑提取到第三个 Command 类中。这让我们可以限制Window 的责任,也可以避免使用方法变量的技巧(我们传递给按钮对象的command 只是另一个对象):

class HelloWorldCommand:

    def execute(self):
        print("Hello world")


class Window:

    def __init__(self):
        self.my_button = Mybutton(
            HelloWorldCommand()
        )

class Mybutton:

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

    def a_ramdom_fcn(self):
        self.command.execute()


win = Window()
win.my_button.a_ramdom_fcn()

【讨论】:

    【解决方案2】:

    首先,修正错别字:abc 的 init 方法中缺少 :,这两个类都应该是 __init__(带两个下划线)。


    看来你已经把自己转过来了。您已经使用组合正确设置:abc 有一个Mybutton,看起来您正确地将函数传递给Mybutton,以便它可以执行它。事实上,如果你这样做了,你的代码就会像写的那样工作,例如

    a = abc(master)  # no context for what master is, but I assume you have it
    a.B1.A_ramdom_fcn()
    

    按照您的设置方式,您不想在主程序中导入和创建Mybutton 的实例(abc 属于什么?)。您想要导入并创建 abc 的实例。然后,您可以访问他们的内部Mybutton,就像我在上面的示例中所示。这是有效的,因为当您在 abc 构造函数中将 self.cmd 传递给 Mybutton 构造函数时,它已经是您正在构造的 abc 的绑定方法。


    作为附录,关于为什么需要这种迂回方法,您可能有一个XY problem。有什么理由不能简单地将abc.cmd 传递给按钮按下处理程序?

    【讨论】:

    • 嗨乔希。谢谢回复。这确实是一个 xy 问题......我的意思是问如何从另一个类访问我的类方法,在这种情况下访问 cmd() 并从 Mybutton 类打印“hello world”我想这样做的原因是创建自定义按钮Tk 中的小部件,所以它看起来更好,我可以说 B1=Mybutton(root, x,y, mycommand) 并调用 abc 类中的命令,但由于它传递给 Mybutton,我必须回调...
    猜你喜欢
    • 2015-07-29
    • 1970-01-01
    • 1970-01-01
    • 2019-07-21
    • 1970-01-01
    • 1970-01-01
    • 2021-03-15
    • 2020-12-07
    相关资源
    最近更新 更多