Search code examples
pythonpython-3.xself

Calling function causes TypeError: missing 1 required positional argument: 'self'


I'm trying to create a Python program that is able to open a youtube video, and then skip the ad in it. Here is what I have:

class MusicPlayer():
    def __init__(self):
        self.driver = webdriver.Safari()
        self.driver.get("https://www.youtube.com/watch?v=suia_i5dEZc")
        sleep(7)
        skipAd = self.driver.find_element_by_class_name('ytp-ad-skip-button-container')

        def skipAdFunction(self):
            threading.Timer(3,skipAdFunction).start()
            if(skipAd.is_enabled() or skipAd.is_displayed()):
                skipAd.click()
        skipAdFunction()

However, I'm not sure why this is happening, but I keep getting this error:

Traceback (most recent call last):
  File "aivoices.py", line 52, in <module>
    MusicPlayer()
  File "aivoices.py", line 17, in __init__
    skipAdFunction()
TypeError: skipAdFunction() missing 1 required positional argument: 'self'

It has something to do with self, but I'm sure if I'm supposed to have it or not. Can someone also explain me whether I need it in this occasion or not?


Solution

  • You should instead write self.skipAdFunction() when you call the function.

    Alternatively, you can define skipAdFunction outside of the class and you won't have to mention self anywhere.

    Edit:

    As per Charles' comment, this is incorrect, my apologies. When you have a nested function defined within a class method, python does not expect/require you to have the positional argument self. Therefore, you can fix it like so:

    class MusicPlayer():
        def __init__(self):
            # stuff you had here
            def skipAdFunction():
                threading.Timer(3,skipAdFunction).start()
                if(skipAd.is_enabled() or skipAd.is_displayed()):
                    skipAd.click()
            skipAdFunction()