如何从anohter文件访问在另一个类的一个文件中创建的对象?

时间:2019-01-18 01:11:34

标签: python-3.x

我正在创建一个快速的数值求解器,其中所有变量在不同文件之间共享。因此,项目中的所有文件都必须访问包含变量的对象。

这是一个求解拉普拉斯方程的数值应用程序。不幸的是,我的经验基本上是关于Fortran90和MPI的,而没有关于OOP的经验。我想使每个文件上的每个“子例程”保持隔离。这就是我在CFD中用程序开发数千行代码的方法。我想对对象使用相同的想法。

file1.py
class Variables:
   def __init__():
      self.AnodeLength = 2.0
      self.CathodeLength = 1.0
      self.Length = 0.0
 ......
 #    a bunch of more variables

file2.py
from file1 import *

ME = Variables()
# ME is the object from the class Variables from file1.py and it contains all the variables needed for the computation.
GridSolver = Grid()
GridSolver.GridGeneration    #Here is the problem

file3.py
from file2 import *
class Grid:
    def GridGeneration(self):
        EM.Length = EM.AnodeLength + EM.CathodeLength

当我执行前面的代码时,它给了我EM错误,无法识别。我认为这是有道理的,因为EM不在该类的范围内,而是在我启动的file2.py中。

  1. 是否可以将对象作为参数传递给类?例如,如果我可以将对象EM传递到Grid类中,则可以从Grid类中的该对象中提取属性,我想可以解决我的问题。

  2. 是否可以使对象成为全局对象,以便同一目录中的每个类(来自每个文件)都可以访问该对象?

1 个答案:

答案 0 :(得分:0)

根据您当前的方法,可以将对象作为参数传递给类。您更新后的代码如下所示:

file1.py

class Variables:
   def __init__():
      self.AnodeLength = 2.0
      self.CathodeLength = 1.0
      self.Length = 0.0
 ......
 #    a bunch of more variables

file2.py

from file1 import *

ME = Variables()
# ME is the object from the class Variables from file1.py and it contains all the variables needed for the computation.
GridSolver = Grid()
GridSolver.GridGeneration(ME)    #Passing the object as parameter

file3.py

from file2 import *
class Grid:
    def GridGeneration(self, EM):
        EM.Length = EM.AnodeLength + EM.CathodeLength

如您所见,我们将GridGeneraion更改为接受其他参数。 现在,让我向您展示所有标准模块使用常量的方式。

file1.py

ANODE_LENGTH = 2.0
CATHODE_LENGTH = 1.0
LENGTH = 0.0
#  a bunch of more variables

file2.py

GridSolver = Grid()
GridSolver.GridGeneration()    # no need to pass parameter

file3.py

import file1
class Grid:
    def GridGeneration(self):
        EM.Length = file1.ANODE_LENGTH + file1.CATHODE_LENGTH

上面的代码有任何问题,任何人都可以将值分配给这些常量。因此在python中,没有常量。这意味着任何人都可以更改ANODE_LENGTH=100这样的值。虽然,您可以基于this post

实现常量实现

因此您的 file2.py 实现将更改如下

class _file2:
    class ConstError(TypeError): pass
    def __setattr__(self,name,value):
        if self.__dict__.has_key(name):
            raise self.ConstError, "Can't rebind const(%s)"%name
        self.__dict__[name]=value
import sys
sys.modules[__name__]=_file2()
相关问题