相关疑难解决方法(0)

Python:绑定一个未绑定的方法?

在Python中,有没有办法绑定未绑定的方法而不调用它?

我正在编写一个wxPython程序,对于某个类,我认为将所有按钮的数据组合在一起作为类级别的元组列表是很好的,如下所示:

class MyWidget(wx.Window):
    buttons = [("OK", OnOK),
               ("Cancel", OnCancel)]

    # ...

    def Setup(self):
        for text, handler in MyWidget.buttons:

            # This following line is the problem line.
            b = wx.Button(parent, label=text).Bind(wx.EVT_BUTTON, handler)
Run Code Online (Sandbox Code Playgroud)

问题是,由于所有的值handler都是未绑定的方法,我的程序在一个壮观的火焰中爆炸,我哭泣.

我在网上寻找解决方案似乎应该是一个相对简单,可解决的问题.不幸的是我找不到任何东西.现在,我正在functools.partial尝试解决这个问题,但有没有人知道是否有一种干净,健康,Pythonic的方式将未绑定的方法绑定到一个实例并继续传递它而不调用它?

python methods bind class

108
推荐指数
4
解决办法
4万
查看次数

Python:如何将类的功能分成多个文件?

我知道这已被问过几次,但我不能完全理解以前的答案和/或我认为解决方案并不能代表我正在拍摄的内容.我仍然是Python的新手,所以我很难搞清楚这一点.

我有一个主类,它有一个不同功能的TON.它变得越来越难以管理.我希望能够将这些功能分成单独的文件,但我发现很难找到一个好方法.

这是我到目前为止所做的:

main.py

import separate

class MainClass(object):
    self.global_var_1 = ...
    self.global_var_2 = ...

    def func_1(self, x, y):
        ...
    def func_2(self, z):
        ...
    # tons of similar functions, and then the ones I moved out:

    def long_func_1(self, a, b):
        return separate.long_func_1(self, a, b)
Run Code Online (Sandbox Code Playgroud)

separate.py

def long_func_1(obj, a, b):
    if obj.global_var_1:
        ...
    obj.func_2(z)
    ...
    return ...
# Lots of other similar functions that use info from MainClass
Run Code Online (Sandbox Code Playgroud)

我这样做是因为如果我这样做:

obj_1 = MainClass()

我希望能够做到:

obj_1.long_func_1(a, b)

代替:

separate.long_func_1(obj_1, a, b)

我知道这似乎有点挑剔,但我想要开始的所有代码,obj_1.所以没有混乱. …

python file object decorator

14
推荐指数
3
解决办法
7906
查看次数

标签 统计

python ×2

bind ×1

class ×1

decorator ×1

file ×1

methods ×1

object ×1