Zach Bonfil
Zach Bonfil

Reputation: 321

TypeError: gettext() missing 1 required positional argument: 'self' - python

I'm new to python and I'm tring to make a class for a modul which checking curses in texts. can someone help please?

import urllib

class Checktext:

    def __init__(self, text):
        self.text = text

    def gettext(self):
        file = open(self.text, "r")
        filetext = open.read()
        for word in filetext.split():
            openurl = urllib.request.urlopen("http://www.wdylike.appspot.com/?q=" + word)
            output = openurl.read()
            truer = "true" in str(output)
            print(truer)

s = Checktext(r"C:\Users\Tzach\.atom\Test\Training\readme.txt") 
Checktext.gettext()

Upvotes: 0

Views: 3139

Answers (2)

pepr
pepr

Reputation: 20762

The urllib is a package. You have to import the module request that is located in the package:

import urllib.request

The open(filename) return a file object. You want to call the method of that object:

filetext = file.read()

And as G. Anderson wrote, you want to call s.gettext() instead of Checktext.gettext(). The self inside is actually equal to the s outside. If you want to be weird then you actually can use also:

Checktext.gettext(s)

Notice the s passed as your missing parameter. Here Python actually reveals how the Object Oriented things are implemented internally. In majority of OO languages, it is carefully hidden, but calling a method of an object is always internally translated as passing one more special argument that points to the instance of the class, that is the object. When defining a Python method, that special argument is explicitly named self (by convention; you can name it differently -- you can try as the lecture, but you should always keep that convention).

Thinking about it thoroughly, you can get the key idea of the hidden magic of an OO language syntax. The instance of the class (the object) is actually only a portion of memory that stores the data part, and that is passed to the functions that implement the methods. The Checktext.gettext is actually the function, the s is the object. The s.gettext() is actually only a different way to express exactly the same. AS s is the instance of the Checktext class, the fact is stored inside the s. Therefore, the s.gettext() creates the illusion that the rigth code will be called magically. It fits with the trained brain better than the function approach if the s is thought as a tangible something.

Upvotes: 2

G. Anderson
G. Anderson

Reputation: 5955

You declared s as a new Checktext object, so you need to call s.gettext() not an un-instantiated Checktext.gettext(), as that has no self to refer to

Upvotes: 2

Related Questions