使用Python将代码直接导入脚本?

时间:2010-11-27 22:30:33

标签: python class import merge include

我正在开发一个PyQT4应用程序,而且我很难一次浏览所有代码。我知道import foo语句,但我无法弄清楚如何将一大块代码直接导入到我的脚本中,比如BASH source foo语句。 / p>

我正在尝试这样做:

# 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完成吗?

谢谢!

3 个答案:

答案 0 :(得分:4)

出于某种原因,我的第一个想法是多重继承。但为什么不尝试正常的继承?

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

利用pythons功能进行多重继承,可以使用来自两个源的方法创建一个新类。

答案 1 :(得分:3)

你想要execfile()。虽然你真的没有,但自从重新定义一个类,呃......重新定义它。

答案 2 :(得分:0)

在python中进行猴子修补几乎不会以同样的方式工作。这通常被认为是不好的形式,但如果你想这样做,你可以这样做:

# File 'functions.py'

class foo(asd.fgh):
  def __init__(self):
    print 'foo'

导入的模块保持不变。在导入模块中,我们做的事情完全不同。

# File 'main.py'

import functions

def qwerty(self):
  print 'qwerty'

functions.foo.qwerty = qwerty

请注意,没有其他类定义,只是一个裸函数。然后我们将该函数添加为该类的属性。