Jynrei
Jynrei

Reputation: 35

AttributeError when calling class2 within class1, class1 has no __init__ attribute

I'm new to OOP and am trying to use two classes. I'm trying to feed an attribute that isn't created until Class1 is run to Class2, but I'm getting an AttributeError when I run Class1.

class Class1():
    #some code....

    def function1():
        x=5
        number=2
        test=class2(x)

        answer=Class2.function2(Class2,number)
        print(answer)    

class Class2():
    def __init__(self, y):
        self.y=y

    def function2(self, z):
        calculated_answer=self.y+z
        return calculated_answer

    #several more functions that also use y

I'm trying to avoid repetition of defining y as x in every new function in Class2, so I thought I could just run Class2 with x and then use function2 with number to print 7. Instead I get: AttributeError: type object 'Class2' has no attribute 'y'.

Originally I thought I was misunderstanding __init__, so I ran this code to make sure:

class Class2():
    def __init__(self, y):
        self.y=y

    def function2(self, z):
        calculated_answer=self.y+z
        return calculated_answer

x=5
test=class2(x)

But this works fine when I type test.function2(2) into the shell, returning 7 as expected.

I think I must be misunderstanding how to use Class2, but I can't figure out what I'm doing wrong.

How do I get rid of this error without just defining x in every function in Class2?

Upvotes: 1

Views: 145

Answers (2)

gmds
gmds

Reputation: 19905

The reason is this line:

answer = Class2.function2(Class2, number)

First, we must note that the following are equivalent:

class A:

    def method(self):
        pass

A().method()
A.method(A())

I believe you want to do something like this:

class2 = Class2()
answer = class2.function2(number)

If we perform the above conversion, that would be the same as this:

answer = Class2.function2(Class2(), number)

Note that your original code is missing () after Class2, which means that instead of passing an instance of Class2 to the method, you are passing the type object Class2 itself, which doesn't make sense.

Upvotes: 1

Rahul
Rahul

Reputation: 11560

It is very difficult to understand your code but one obvious mistake is at this line.

 answer=Class2.function2(Class2,number)

Change it to

 answer = test.function2(number)

When you create object by calling it with required init argument, you don't need to pass self parameter while calling functions of the class. It is automatically passed.

Upvotes: 0

Related Questions