Home > Net >  How to overload the add operator to return the length of two string when they are added?
How to overload the add operator to return the length of two string when they are added?

Time:11-29

I am trying to create a class diffStr that behaves like str except, when a user tries to add or multiply two strings, the output is the length of each string added or multiplied (respectively).

My code -

class diffStr:

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

  def __add__(self, other):
   return len(self.str1)   len(other.str1)
  
  def __mul__(self, other):
    return len(self.str1) * len(other.str1)

x = diffStr('hi')
print(x 'hello') # supposed to print 7 (2 5)
print(x*'hello') # supposed to print 10 (2*5)

I am sure I am doing something wrong because I keep getting the following error message when I try to run the code -

AttributeError: 'str' object has no attribute 'str1'

As you can probably tell, I am a noob at programming and trying my best to learn. I would appreciate any help in fixing this block of code. Thank you.

CodePudding user response:

With x 'hello', you're passing a str object of 'hello' as the other argument to x.__add__, which evaluates other.str1, and since a str object has no str1 attribute, you get the said exception.

A better-rounded approach that helps make the and * operators work for both str and diffStr operands would be to implement the __len__ method for diffStr, so that you can simply call the len function on the other argument regardless of its type:

class diffStr:
    def __init__(self, str1):
        self.str1 = str1

    def __add__(self, other):
        return len(self.str1)   len(other)

    def __mul__(self, other):
        return len(self.str1) * len(other)

    def __len__(self):
        return len(self.str1)

x = diffStr('hi')
print(x   'hello')
print(x * 'hello')
print(x   diffStr('hello'))
print(x * diffStr('hello'))

This outputs:

7
10
7
10
  • Related