Search code examples
pythonpython-3.xclassmethodsself

Issues with declaration method ( & self) in python


While trying to experiment with classes and methods, and how to pass variables between them, I wrote a couple of scripts to try to understand the mechanics. In doing so I hit an issue where one of my functions is un-defined:

NameError: name 'exclaim' is not defined

I thought use of self might resolve but i just loop round into

NameError: name 'self' is not defined

I've come across several sources regarding this leading me to look at indentation levels of methods, and calling via HelloWorld.exclaim() which hits the same issue.

please see my code: (script1)

import datasource

class HelloWorld:

    def exclaim():
        number1 = input("enter a number")
        datasource.Class2.method3.impvariable1 = number1

    def main():
        HelloWorld.exclaim()
        print(datasource.Class1.method1.variable1)
        print(datasource.Class2.method2.variable2)
        print(datasource.Class2.method3.variable3)

    if __name__ == '__main__':
        main()

Script2:

#datasource.py
class Class1:
    def method1():
        variable1 = "Hello "

class Class2:
    def method2():
        variable2 = "World"
    def method3():
        impvariable1 = 0
        variable3 = "!"
        for x in range(impvariable1):
            variable3 = variable3 + "!"

I also tried (amount 100's of other iterations)

    #datahandler.py
import datasource

class HelloWorld:

    def exclaim(self):
        number1 = input("enter a number")
        datasource.Class2.method3.impvariable1 = number1

def main(self):
    HelloWorld.exclaim(self)
    print(datasource.Class1.method1.variable1)
    print(datasource.Class2.method2.variable2)
    print(datasource.Class2.method3.variable3)

if __name__ == '__main__':
    main(self)

which produces;

NameError: name 'self' is not defined

Solution

  • import datasource
    
    class HelloWorld:
    
        def exclaim(self):
            number1 = input("enter a number")
            datasource.Class2.method3.impvariable1 = number1
    
    def main():
        obj = HelloWorld()
        obj.exclaim()
        print(datasource.Class1.method1.variable1)
        print(datasource.Class2.method2.variable2)
        print(datasource.Class2.method3.variable3)
    
    if __name__ == '__main__':
        main()