Mar*_*son 10 python methods import
我想知道是否可以将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)
Run Code Online (Sandbox Code Playgroud)
to_import_from.py:
def external_method(self, arg1, arg2):
if self.flag:
#doing something
#...many more methods
Run Code Online (Sandbox Code Playgroud)
就我而言,to_import_from.py是机器生成的,并包含许多方法.我宁愿不将它们复制粘贴到main_module.py中或逐个导入它们,但要将它们全部识别为Instrument类的方法,就像它们已在那里定义一样:
>>> instr = Instrument()
>>> instr.direct_method(arg1)
>>> instr.external_method(arg1, arg2)
Run Code Online (Sandbox Code Playgroud)
谢谢!
Ant*_*sma 10
人们似乎在过度思考这一点.方法只是类构造范围中的函数值局部变量.所以以下工作正常:
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)
Run Code Online (Sandbox Code Playgroud)
小智 7
我认为你想要的东西在Python中是不可能的.
但是,您可以尝试以下方法之一.
to_import_from.py,也在那里添加非生成的东西.这样,所有方法都在同一个类定义中.to_import_from.py包含内容的类定义的仪器类继承.换句话说,在to_import_from.py:
class InstrumentBase(object):
def external_method(self, arg1, arg2):
if self.flag:
...
Run Code Online (Sandbox Code Playgroud)
然后在main_module.py:
import to_import_from
class Instrument(to_import_from.InstrumentBase):
def __init__(self):
...
Run Code Online (Sandbox Code Playgroud)
它比你想象的容易:
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
Run Code Online (Sandbox Code Playgroud)
完成!
虽然让机器生成的代码生成类定义并从中进行子类化将是一个更简洁的解决方案.
很抱歉,这是一种“你不应该在墙上钉钉子”的答案,但你忽略了 python 类定义的要点。你应该将类及其所有方法放在它自己的 python 文件中,然后放在你的main_module.pydo中
from instrument import Instrument
Run Code Online (Sandbox Code Playgroud)
如果您计划对多个类使用这些方法,则应该考虑子类化。在您的情况下,机器生成的文件可能包含Instrument继承自的基类。
最后,为您的类提供一个良好的文档字符串,向其用户解释 API,因此不需要使用“头文件”作为类的概述。
你可以用这个__getattr__方法来做到这一点
外部.py
def external_function(arg):
print("external", arg)
Run Code Online (Sandbox Code Playgroud)
主要.py:
import external
class Instrument(object):
def __getattr__(self, name):
if hasattr(external, name):
return getattr(external, name)
else:
return Object.__getattr__(self, name)
def direct_method(self, arg):
print("internal", arg)
i = Instrument()
i.direct_method("foo")
i.external_function("foo")
Run Code Online (Sandbox Code Playgroud)