我正在开发 PyQT4 应用程序,一次浏览所有代码对我来说越来越困难。我知道 import foo
语句,但我不知道如何让它直接将一大块代码导入我的脚本,比如 BASH source foo
语句。
我正在尝试这样做:
# File 'functions.py'
class foo(asd.fgh):
def __init__(self):
print 'foo'
这是第二个文件。
# File 'main.py'
import functions
class foo(asd.fgh):
def qwerty(self):
print 'qwerty'
我想从两个单独的文件中包含代码或合并类减速。在 PHP 中,有 import_once('foo.php')
,正如我之前提到的,BASH 有 source 'foo.sh'
,但我可以用 Python 完成吗?
谢谢!
最佳答案
出于某种原因,我的第一个想法是多重继承。但为什么不尝试正常的继承呢?
class foo(functions.foo):
# All of the methods that you want to add go here.
有什么原因导致这行不通吗?
既然你只想合并类定义,你为什么不这样做:
# main.py
import functions
# All of the old stuff that was in main.foo is now in this class
class fooBase(asd.fgh):
def qwerty(self):
print 'qwerty'
# Now create a class that has methods and attributes of both classes
class foo(FooBase, functions.foo): # Methods from FooBase take precedence
pass
或
class foo(functions.foo, FooBase): # Methods from functions.foo take precedence
pass
这利用了 python 的多重继承能力来创建一个包含来自两个源的方法的新类。
关于python - 使用 Python 将代码直接导入脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4294266/