代码之家  ›  专栏  ›  技术社区  ›  Blender

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

  •  1
  • Blender  · 技术社区  · 14 年前

    我正在开发一个PyQT4应用程序,同时浏览所有代码变得非常困难。我知道 import foo 语句,但我不知道如何使它导入一段代码 直接地 写进我的剧本里,就像舞会 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来完成这个任务吗?

    谢谢!

    3 回复  |  直到 14 年前
        1
  •  4
  •   aaronasterling    14 年前

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

    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的多重继承功能创建一个新类,其中包含来自两个源的方法。

        2
  •  3
  •   Ignacio Vazquez-Abrams    14 年前

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

        3
  •  0
  •   SingleNegationElimination    14 年前

    python中的monkey补丁并不能以几乎相同的方式工作。这通常被认为是不好的形式,但如果你想这样做,你可以这样做:

    # 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
    

    注意,没有额外的类定义,只有一个简单的函数。然后将函数作为类的属性添加。