-3

I am new in programming and I have faced a problem for which I can't find an answer... So here it is:

`class MyClass:
    def printsmth():
        print("Hello")
    def main():
        printsmth()
    if __name__ == '__main__':main()`

I get an error which says :

Traceback (most recent call last):
  File "untitled.py", line 1, in <module>
    class MyClass:
  File "untitled.py", line 6, in MyClass
    if __name__ == '__main__':main()
  File "untitled.py", line 5, in main
    printsmth()
NameError: name 'printsmth' is not defined

Code included is just an example, but it is the same error that I get on my real code, if for example I would transfer my code from main() to if name == 'main' than it works perfectly. The thing is that I want to relaunch main() method in some parts of the code but I haven't even gone to that because I can't think of a solution to this error:/ Can you help me?

P.S I tried to move main() and if name == 'main' from MyClass and it didn't worked.

vaultah
  • 44,105
  • 12
  • 114
  • 143
  • https://docs.python.org/2/tutorial/classes.html#python-scopes-and-namespaces - you need to get familiar with essential Python concepts (in this case scopes). – Łukasz Rogalski Apr 12 '16 at 16:40
  • 2
    It looks as if you are trying to write Java in python. That is the only reason I can think of for unbound functions inside a `class`. Follow any python tutorial of the thousands out there for further clarification. – C Panda Apr 12 '16 at 16:47

1 Answers1

1

You are forgetting to pass self as the first parameter of your methods. Once you do this, you can callself.printsmth() as a method. Right now it's confused because you're calling it as a function rather than a method.

class MyClass:
    def printsmth(self):
        print("Hello")
    def main(self):
        self.printsmth()
Will
  • 4,299
  • 5
  • 32
  • 50