Home > Blockchain >  I cant make a class which deletes special signs
I cant make a class which deletes special signs

Time:12-18

I cant make a class which deletes special signs

class StripChars:
    def __init__(self, chars):
        self.__chars = chars

    def __call__(self, *args, **kwargs):
        if not isinstance(args, str):
            raise TypeError('Argument must be str')

        return args.strip(self.__chars)

s = StripChars('?!.;')
res = s('Hello World!')
print(res)

It always raises TypeError

CodePudding user response:

args is a tuple, not a string. Use args[0] instead.

def __call__(self, *args, **kwargs):
    if not isinstance(args[0], str):
        raise TypeError('Argument must be str')

    return args[0].strip(self.__chars)

Or, if you always input 1 parameter at a time, you can do like the code below. There is no need for *args.

def __call__(self, string):
    if not isinstance(string, str):
        raise TypeError('Argument must be str')

    return string.strip(self.__chars)

CodePudding user response:

For more than one parameters.

class StripChars:
    def __init__(self, chars):
        self.__chars = chars

    def __call__(self, *args, **kwargs):
        
        if not any(isinstance(arg, str) for arg in args):
            raise TypeError('Argument must be str')

        return [arg.strip(self.__chars) for arg in args]

s = StripChars('?!.;')
res = s('Hello World!', "What?")
print(res)
# ['Hello World', 'What']

CodePudding user response:

Thats because args in this case is tuple of positional arguments and string that you passed to s instance is first argument of this tuple. You can use

if not isinstance(args[0], str):
...

or the better choice in my opinion is

def __call__(self, some_string):
    if not isinstance(some_string, str):
    ...

My bad, I am a bit late and good answer is already given :)

  • Related