0

Please see the sample code:

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)))

I am trying to understand how to call other function within same class. As you can see, I am trying to find odd numbers from common_numbers function.

Please understand this is sample work. I know there are plenty of solutions with or withouth using classes to get propriet result. But in this case, I don't need result, I would really appretiate if you could help me understand the calling other function within class. Sorry for my English and Thank you in advance.

1 Answer 1

4

You're getting the error because you never actually define self.variable_list. It's only defined once you call common_numbers(), but you never do that. You can define it when initiating:

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))

or after initiating, but before calling 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))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.