Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from collections import UserString
- class MyString(UserString):
- def __init__(self, s):
- super().__init__(s)
- if len(self) > 30:
- raise ValueError(f"str length is larger than 30: {s}")
- def __eq__(self, other):
- if not isinstance(other, (str, self.__class__)):
- return False
- return str(self).lower().__eq__(str(other).lower())
- def __ne__(self, other):
- return not self.__eq__(other)
- def __lt__(self, other):
- if not isinstance(other, (str, self.__class__)):
- raise TypeError(
- f"not supported between instances of '{self.__class__.__name__}' and '{other.__class__.__name__}'"
- )
- return str(self).lower().__lt__(str(other).lower())
- def __le__(self, other):
- if not isinstance(other, (str, self.__class__)):
- raise TypeError(
- f"not supported between instances of '{self.__class__.__name__}' and '{other.__class__.__name__}'"
- )
- return str(self).lower().__le__(str(other).lower())
- def __gt__(self, other):
- if not isinstance(other, (str, self.__class__)):
- raise TypeError(
- f"not supported between instances of '{self.__class__.__name__}' and '{other.__class__.__name__}'"
- )
- return str(self).lower().__gt__(str(other).lower())
- def __ge__(self, other):
- if not isinstance(other, (str, self.__class__)):
- raise TypeError(
- f"not supported between instances of '{self.__class__.__name__}' and '{other.__class__.__name__}'"
- )
- return str(self).lower().__ge__(str(other).lower())
- # testing
- # create instance
- foo_int = MyString(123)
- print(foo_int)
- foo_float = MyString(123.0)
- print(foo_float)
- foo = MyString("Foo")
- # concat
- foobar = foo + "bar"
- assert isinstance(foobar, MyString)
- foobar = "foo" + MyString("bar")
- assert isinstance(foobar, MyString)
- assert foobar == "foobar"
- # concat error
- try:
- MyString("1" * 29) + "11"
- except ValueError as e:
- print(e)
- # multiply
- foo3 = foo * 10
- # multiply error
- try:
- foo * 11
- except ValueError as e:
- print(e)
- # total ordering
- assert foo == "foo"
- assert foo == "Foo"
- assert foo >= "foo"
- assert foo >= "Foo"
- assert foo <= "foo"
- assert foo <= "Foo"
- assert foo != "bar"
- assert foo != "BAR"
- assert foo > "foa"
- assert foo < "foz"
- assert foo <= "foz"
- assert foo >= "foa"
- assert "foo" == foo
- assert "Foo" == foo
- assert "foo" >= foo
- assert "Foo" >= foo
- assert "foo" <= foo
- assert "Foo" <= foo
- assert "bar" != foo
- assert "BAR" != foo
- assert "foa" < foo
- assert "foz" > foo
- assert "foz" >= foo
- assert "foa" <= foo
Add Comment
Please, Sign In to add comment