为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)
谢谢!
8 个回答
8
其实比你想的要简单:
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
完成了!
不过,如果让机器生成的代码直接生成一个类的定义,然后从这个类继承,会是一个更整洁的解决方案。
20
大家似乎在想得太复杂了。方法其实就是在类的构造范围内的函数值局部变量。所以下面的代码是可以正常工作的:
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)
8
我觉得你想要的在Python中直接实现是不太可能的。
不过,你可以尝试以下几种方法。
- 在生成
to_import_from.py
文件的时候,把那些非生成的内容也加进去。这样的话,所有的方法都在同一个类定义里。 - 让
to_import_from.py
文件包含一个基类的定义,然后让Instrument类去继承这个基类。
换句话说,在 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):
...