Python Forum

Full Version: Call method from another method within a class
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Not sure if this is the right thinking but anyway, this is what I'm trying to do:

I have a Class which includes some variables and some methods. The class has itself some code thats executed where instansiating an object 'a('Call a method')'. I can call method a() but when method a() calls method b() it all fails.

Whats the reason for this and how should it be solved?
It's when the call b('aa') executes I get the error: 'NameError: global name 'b' is not defined'
Why can't method a() reach method b()?

class TestClass:

    def __init__(self):
        pass

    def b(name):
        print '---b---', name

    def a(name):
        print '---a---', name
        b('aa')

    a('Call a-method')
it will work, but you should use python 3.7.4
class TestClass:
    def __init__(self, name):
        self.methoda(name)

    def methodb(self, name):
        print(f"---b---{name}")
 
    def methoda(self, name):
        print(f"---a---{name}")
        self.methodb("aa")
 
def tryit():
    TestClass("Call a-method")
    

if __name__ == "__main__":
    tryit()
Thanks! Tried to tag the python code according to the instructions.

I modified your code slightly so that it works in Python 2.7
The difference is that I want to call method a from within the class. As you see in my firsst example, the
intendation of the call "a('Call a-method')" is inside the class, not outside. My first example works if I comment line #13 (b('aa')).

class TestClass:
    def __init__(self, name):
        self.methoda(name)

    def methodb(self, name):
        print("---b---{}".format(name))

    def methoda(self, name):
        print("---a---{}".format(name))
        self.methodb("aa")

    self.methoda('Call a-method from within class') # This doesn't.

TestClass("Call a-method") # This works
python 2, see: https://pythonclock.org/

You can't do this in a class
self.methoda('Call a-method from within class') # This doesn't.
you must use method