从前一个类访问类实例

时间:2015-06-30 00:11:58

标签: python

我有2个文件。第一个文件是:

import file1

Class MyTest:
    .
    .
     def Test(self):
          my_config = file1.Check_my_config()

     def add_something(self):
          do something
    .
    .

file1 文件如下所示:

Class Check_my_config(object):

    def __init__(self, var1, var2):
        do_something
        MyTest.self.add_something()

如何访问上一个类实例?

1 个答案:

答案 0 :(得分:1)

将其作为参数传递。

import file1

Class MyTest:
    .
    .
     def Test(self):
          # pass two required arguments e.g. a and b
          # (as defined by Check_my_config's __init__) and self
          my_config = file1.Check_my_config(a, b, self)

     def add_something(self):
          do something
    .
    .
Class Check_my_config(object):

    def __init__(self, var1, var2, mytest): # add a mytest parameter
        do_something
        mytest.add_something() # call a method bound to the passed mytest object