python - 在同一个类中调用函数

时间:2016-06-09 21:20:53

标签: python function class

请参阅示例代码:

a = [1,2,3,4,5]  # main list

b = [4,5,6]   #variable list nr1
c = [1,2]    #variable list nr2

class union(object):
    def __init__(self, name):
        self.name = name

    def common_numbers(self, variable_list):
        self.variable_list = variable_list
        for x in self.name:
            if x in self.variable_list:
                yield(x)

    def odd_numbers(self, odds):
        self.odds = odds
        for x in self.variable_list:
            if not x % 2 == 0:
                yield x

''' I receive: builtins.AttributeError: 'union' object has no attribute 'variable_list'.'''


x = union(a)
print(list(x.odd_numbers(c)))

我试图了解如何在同一个类中调用其他函数。如您所见,我试图从common_numbers函数中找到奇数。

请理解这是样本工作。我知道有很多解决方案,有或没有使用类来获得propriet结果。但是在这种情况下,我不需要结果,如果你能帮助我理解课堂上的其他功能,我真的很乐意。对不起我的英文,并提前谢谢。

1 个答案:

答案 0 :(得分:4)

您收到错误是因为您从未真正定义过self.variable_list。它只在你调用common_numbers()时定义,但你永远不会这样做。您可以在启动时定义它:

class union(object):
    def __init__(self, name, variable_list):
        self.name = name
        self.variable_list = variable_list

    def common_numbers(self):
        for x in self.name:
            if x in self.variable_list:
                yield(x)
x = union(a, b)
print list(x.odd_numbers(c))

或在启动之后,但在调用odd_numbers之前:

class union(object):
    def __init__(self, name):
        self.name = name

    def common_numbers(self):
        for x in self.name:
            if x in self.variable_list:
                yield(x)

x = union(a)
x.variable_list = b
print list(x.odd_numbers(c))