Search code examples
pythonpython-3.xfunctionpython-typingself

Function in a class doesn't require self parameter


Trying to make a Python module which provides functions for user input. My code looks like this:

class PyInput:
    def inputString(prompt = "Enter a string: >>> "):
        userInput = input(prompt)
        return userInput

I'm receiving the following error when I run the function:

Instance methods should take a "self" parameter

I have tried to add a self parameter to the function, but this requires the user to make an object of the class first, which isn't what I want. Is there a way to define a function within a class that so it doesn't take a self parameter?

I'm running Python 3.11 on a Windows 11 64-bit laptop.


Solution

  • Actually, there is a way to define functions inside a class without the self parameter if you decorate it using @staticmethod. For example:

    class Example:
    
        @staticmethod
        def answer():
            print('42')