Python Forum
Call method from another method within a class - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Call method from another method within a class (/thread-21037.html)



Call method from another method within a class - anteboy65 - Sep-11-2019

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



RE: Call method from another method within a class - Larz60+ - Sep-11-2019

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



RE: Call method from another method within a class - anteboy65 - Sep-11-2019

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



RE: Call method from another method within a class - Larz60+ - Sep-11-2019

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