Unknown Shin
Unknown Shin

Reputation: 119

How to call another class method that includes the other method?

I have a class below:

    class Test:
        def alpha(self):
            a = 5
            return a
    
        def bravo(self):
            alp = self.alpha()
            c = 2
            solution = alp + c
            print(solution)
            return solution

and I am trying to write a new class that calls Test.bravo(), but having an error due to Test.alpha inside of it.

How can I write a new class? below is what I did:

    class Test2:
        def charlie(self):
            call_bravo = Test.bravo(self)
            print(call_bravo)

    def main():
        tst = Test()
        tst.bravo()
    
        tst2 = Test2()
        tst2.charlie()

    if __name__ == '__main__':
        main()

Upvotes: 0

Views: 38

Answers (2)

Albert Alberto
Albert Alberto

Reputation: 950

The solution below works correctly.

class Test:

    def alpha(self):
        a = 5
        return a

    def bravo(self):
        alp = self.alpha()
        c = 2
        solution = alp + c
        print(solution)


class Test2:
    def charlie(self):
        call_bravo = Test()
        res = call_bravo.bravo()
        print(res)

def main():
    tst = Test()
    tst.bravo()

    tst2 = Test2()
    tst2.charlie()

if __name__ == '__main__':
    main()

Upvotes: 1

Prune
Prune

Reputation: 77850

I expect that your error is because you're trying to invoke a method of class Test to operate on an object of Test2.

tst2.Charlie() invokes
Test.bravo(tst2), which invokes
tst2.alpha()

Your problem is that there is no such routine: the only alpha in your design is a method of Test; there is no alpha method for Test2.

In short, you have a fatal design error. Sort out what functionality you want in each class.

Upvotes: 0

Related Questions