Rookie coder: main() missing 1 required positional argument: 'self'?

Question:

This is my first coding class (and first time on the site) and I’m working on a class project. I can’t seem to get my code to run correctly. I’m getting 2 errors and I’ve spent the last 2 hours trying to figure them out. Was wondering if this site would be willing/able to help me out. Code in reply message.

Traceback (most recent call last):
  File "C:UsersArtPycharmProjectspythonProject1main.py", line 69, in <module>
    class Conversion:
  File "C:UsersArtPycharmProjectspythonProject1main.py", line 123, in Conversion
    main()
TypeError: main() missing 1 required positional argument: 'self'
class Conversion:
    def say_hello(self):
        print("Hello! I'm a Conversion:", self)

    def main(self):
        task = Conversion()
        task.say_hello()

    if __name__ == "__main__":
        main()

Note: The original code has been removed, but feel free to look at it in the edit history. This is an MRE provided by wjandrea.

Asked By: Not A Coder

||

Answers:

Looks like you’re thinking like Java, where all functions like main() must be part of a class, but Python doesn’t have that restriction, and plain functions are the norm.

In this case, you have code trying to call main(), but the function is defined within the class, so it would be called as self.main() – if that was what you should be doing, which in this case is not.

Answered By: John Bayko

It looks like you indented the last section wrong and added a self parameter to main for some reason (edit: apparently your IDE did that). Your code should look like this:

class Conversion:
    ...
    
def main():
    ...
   
if __name__ == "__main__":
    main()  # on a separate line only for readability
Answered By: wjandrea
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.