为Python类导入方法

2024-05-16 15:17:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道是否可以将Python类的方法保存在与类定义不同的文件中,如下所示:

main_module.py:

class Instrument(Object):
    # Some import statement?
    def __init__(self):
        self.flag = True
    def direct_method(self,arg1):
        self.external_method(arg1, arg2)

to_import_from.py:

def external_method(self, arg1, arg2):
    if self.flag:
        #doing something
#...many more methods

在我的例子中,to_import_from.py是机器生成的,包含许多方法。我不希望将它们复制粘贴到main_module.py或逐个导入,而是将它们都识别为Instrument类的方法,就像它们是在那里定义的一样:

>>> instr = Instrument()
>>> instr.direct_method(arg1)
>>> instr.external_method(arg1, arg2)

谢谢!


Tags: 方法pyimportself定义maindefmethod
3条回答

比你想象的要容易:

class Instrument(Object):
    def __init__(self):
        self.flag = True
    def direct_method(self,arg1):
        self.external_method(arg1, arg2)

import to_import_from

Instrument.external_method = to_import_from.external_method

完成!

尽管让机器生成的代码生成一个类定义并从中进行子类化是一个更简洁的解决方案。

我认为你想要的东西在Python中是不可能直接实现的。

但是,您可以尝试下列操作之一。

  1. 生成to_import_from.py时,也可以在那里添加未生成的内容。这种方式, 所有方法都在同一个类定义中。
  2. 使to_import_from.py包含一个基类定义,其中 继承。

换句话说,在to_import_from.py中:

class InstrumentBase(object):
    def external_method(self, arg1, arg2):
        if self.flag:
            ...

然后在main_module.py中:

import to_import_from

class Instrument(to_import_from.InstrumentBase):
    def __init__(self):
        ...

人们似乎对此想得太多了。方法只是类构造范围内的函数值局部变量。所以下面的方法很好:

class Instrument(Object):
    # load external methods
    from to_import_from import *

    def __init__(self):
        self.flag = True
    def direct_method(self,arg1):
        self.external_method(arg1, arg2)

相关问题 更多 >