141k views
4 votes
Write a class Example() such that it has a method that gives the difference between the size of strings when the '-' (subtraction) symbol is used between the two objects of the class. Additionally, implement a method that returns True if object 1 is greater than object 2 and False otherwise when the (>) (greater than) symbol is used. For example: obj1 = Example('this is a string') obj2 = Example('this is another one') print(obj1 > obj2) False print(obj1-obj2) 3

User Anssssss
by
5.0k points

1 Answer

6 votes

Answer:

class Example:

def __init__(self, val):

self.val = val

def __gt__(self, other):

return self.val > other.val

def __sub__(self,other):

return abs(len(self.val) - len(other.val))

def main():

obj1 = Example('this is a string')

obj2 = Example('this is another one')

print(obj1 > obj2)

print(obj1 - obj2)

main()

\color{red}\underline{Output:}

User Libelle
by
4.1k points