python-同一类中的调用函数

fil*_*ips 0 python class function

请查看示例代码:

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)))
Run Code Online (Sandbox Code Playgroud)

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

请理解这是示例工作。我知道有很多解决方案,无论是否使用类来获取适当的结果。但是在这种情况下,我不需要结果,如果您能帮助我理解在类中调用其他函数,我将不胜感激。对不起,我的英语,谢谢。

Nat*_*ane 5

因为没有真正定义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))
Run Code Online (Sandbox Code Playgroud)

或在启动之后,但在调用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))
Run Code Online (Sandbox Code Playgroud)