python将值传递给类中的其他函数

时间:2017-02-21 10:04:59

标签: python

我有这段代码:

class test():

    def __init__(self,name,method):
        self.name = name
        self.method = method
        self.values = None

    def A(self):
        self.values = []
        # here, I want to fill the values list when 
        # the method is equal to a certain name (in this case 'a')
        # but I want to use these values in the 'S' function no matter what
        if self.name == 'a':
            for i in range(4):
                self.values.append(i)

        if self.method == 'S':
            return self.S()
        if self.method == 'V':
            return self.V()


    def S(self):
        # here I use the self.values (which are related to a) and 
        # I will make some calculations with other values
        # In terms of simplicity I return only the self.values
        return 'S is called:{0}'.format(self.values)

    def V(self):
        return 'V is called:{0}'.format(self.values)

class basic():

    def __init__(self, name, thelist):
        self.name = name
        self.thelist = thelist

    def startp(self):
        name = self.name
        for i in self.thelist:
            yield i.A()

我有一个定义为test('a','V')的测试类,它有一个名称和一个方法以及一个基本类basic('a',alist),它带有一个名称和一个测试列表。

我的问题出在A()函数中,我希望用值填充列表并将其传递给函数SV

例如,这些值将与变量a相关联。 我想要这些值,以便在S函数中使用它们。

问题在于if self.name =='a'声明。

所以,如果我有一个test('a','S'),一切都很顺利,但我的测试将包含不同的值。

使用以下代码运行代码:

 alist = [ test('a','V'), test('b','S')]
 obs = basic('a',alist).startp()
 for i in obs:
     print(i)

产生:

V is called:[0, 1, 2, 3]
S is called:[]

以:

运行
alist = [ test('a','V'), test('a','S')]

产生:

V is called:[0, 1, 2, 3]
S is called:[0, 1, 2, 3]

因此,逻辑是如果test中的名称等于basic中的名称,则使用此变量值作为参考。但是,它总是一个基本名称等于一个测试名称到alist。所以,我使用if self.name =='a',但正确的是search the list of testswhen self.name == a创建values

---------------更新------------------------

我只想填充values列表,以便始终在S函数中使用它。我必须注意,当test具有方法S时,它将始终具有basic类的不同名称(第一个参数)。

所以,这是有效的:

alist = [ test('a','V'), test('b','S'),test('c','S')]
obs = basic('a',alist).startp()

这不是"有效":

alist = [ test('a','V'), test('a','S'),test('c','S')]
obs = basic('a',alist).startp()

因为test('a','S')使用的名称a等于basic('a',alist)

1 个答案:

答案 0 :(得分:0)

修改方法test.A以获取其他参数,以便您可以检查它而不是对值进行硬编码。

def A(self, name):
    self.values = []
    if self.name == name:
        ...

然后在basic.startp传递basic实例的名称值。

for i in self.thelist:
    yield i.A(self.name)
# Testing
alist = [test('a','V'), test('b','S')]
obs = basic('a',alist).startp()
for i in obs:
    print(i)

#V is called:[0, 1, 2, 3]
#S is called:[]

alist = [test('a','V'), test('a','S')]
obs = basic('a',alist).startp()
#V is called:[0, 1, 2, 3]
#S is called:[0, 1, 2, 3]

alist = [test('a','V'), test('a','S')]
obs = basic('b',alist).startp()
#V is called:[]
#S is called:[]

alist = [test('a','V'), test('b','S')]
obs = basic('b',alist).startp()
#V is called:[]
#S is called:[0, 1, 2, 3]