Search code examples
pythonpython-3.xmethodsstatic-methods

Is it possible to run a print() inside a method without the @staticmethod attribute?


I come from a .NET and Javascript background and I'm working my way up to learn Python (for Raspberry Pi).
Right now I'm trying to figure out OOP in Python and the use of methods and classes. But having a little issue with @staticmethod

class Car(object):
    """description of class"""

    def __init__(self, make, model):
        self.make = make
        self.model = model

    @staticmethod
    def makeFirstNoise():
        print("Vrooooommm!")

    def makeSecondNoise():
        print("Mweeeeeeeeeh!")

This is how I implement my class and try to run both methods.

from Car import Car

mustang = Car('Ford', 'Mustang')
mustang.makeFirstNoise()
mustang.makeSecondNoise()

This is the output:

Vrooooommm! Traceback (most recent call last): File "D:\Dev\T\PythonHelloWorld\PythonHelloWorld\PythonHelloWorld.py", line 5, in <module> mustang.makeSecondNoise() TypeError: makeSecondNoise() takes 0 positional arguments but 1 was given

So question, why can't I execute the second method without my staticmethod attribute? This seems to work if I just return the text directly like this:

def makeSecondNoise():
    return "Mweeeeeeeh!"

print(mustang.makeSecondNoise())

Solution

  • The reason makeSecondNoise is causing an error is because it is automatically passed one argument, self, because it's not declared as a staticmethod. self is the instance of the class that the function was called on. This is ultimately causing the error because makeSecondNoise isn't coded to accept any parameters; it'd be like doing this:

    def something():
        ...
    something("Foo")
    

    Here's an example of how self works:

    >>> class Car:
    ...     def makenoise(self):
    ...         print(self)
    ...
    >>> mustang = Car()
    >>> mustang.makenoise()
    <__main__.Car object at 0x0000000005498B38> # We can see that "self" is a reference to "mustang"
    

    Your problem isn't related to print (I couldn't get your example without print to work either) - it's related to the automatic passing of the self argument.