How can I call the magic method `__contains__`?

I have a contains method in my Sentence class that checks to see if there is a word in a sentence (a string in my case)

I tried checking mine functionTestingif helloexists in hello world, and instead I got this error:

AttributeError: 'Sentence' object has no attribute 'contains'

here is my code

class Sentence:

    def __init__(self, string):
        self._string = string

    def getSentence(self):
        return self._string

    def getWords(self):
        return self._string.split()

    def getLength(self):
        return len(self._string)

    def getNumWords(self):
        return len(self._string.split())

    def capitalize(self):
        self._string = self._string.upper()

    def punctation(self):
        self._string = self._string + ", "

    def __str__(self):
        return self._string

    def __getitem__(self, k):
        return k

    def __len__(self):
        return self._String

    def __getslice__(self, start, end):
        return self[max(0, i):max(0, j):]

    def __add__(self, other):
        self._string = self._string + other._string
        return self._string

    def __frequencyTable__(self):
        return 0

    def __contains__(self, word):
        if word in self._string:
            return True  # contains function!!##


def functionTesting():
    hippo = Sentence("hello world")
    print(hippo.getSentence())
    print(hippo.getLength())
    print(hippo.getNumWords())
    print(hippo.getWords())

    hippo.capitalize()
    hippo.punctation()

    print(hippo.getSentence())

    print(hippo.contains("hello"))


functionTesting()

What do you call a function __contains__? Did I make a mistake in the class method method or make a mistake in the functionTestingcall? I expect to receive True.

+4
source share
2 answers

Note the documentation __contains__,

. true, item self, - false. , .

, __contains__(), __iter__(), __getitem__()

, , in, :

print("hello" in hippo)

: Python 3.x __getslice__. Python 3.0,

__getslice__(), __setslice__() __delslice__() . a[i:j] a.__getitem__(slice(i, j)) ( __setitem__() __delitem__(), ) .

, .


, .

. True, hippo.capitalize() . , self._string HELLO WORLD, . , False.

1: Python True False. __contains__ True, NameError . .

def __contains__(self, word):
    return word in self._string

2: __getslice__

def __getslice__(self, start, end):
    return self[max(0, i):max(0, j):]

i j, . , start end,

def __getslice__(self, start, end):
    return self[max(0, start):max(0, end):]
+7

__contains__, in

like

print "hello" in hippo
+1

All Articles