构建Message类及print重载
时间: 2023-05-18 11:05:53 浏览: 182
override和重载 希望对大家有帮助
好的,下面是构建Message类及print重载的代码示例:
```python
class Message:
def __init__(self, text):
self.text = text
def __str__(self):
return self.text
def __repr__(self):
return f"Message({self.text})"
def __len__(self):
return len(self.text)
def __add__(self, other):
return Message(self.text + other.text)
def __eq__(self, other):
return self.text == other.text
def __lt__(self, other):
return len(self.text) < len(other.text)
def __gt__(self, other):
return len(self.text) > len(other.text)
def __le__(self, other):
return len(self.text) <= len(other.text)
def __ge__(self, other):
return len(self.text) >= len(other.text)
def __contains__(self, item):
return item in self.text
def __getitem__(self, index):
return self.text[index]
def __setitem__(self, index, value):
self.text = self.text[:index] + value + self.text[index+1:]
def __delitem__(self, index):
self.text = self.text[:index] + self.text[index+1:]
def __iter__(self):
return iter(self.text)
def __reversed__(self):
return Message(self.text[::-1])
def __call__(self):
print(self.text)
msg1 = Message("Hello, World!")
msg2 = Message("Goodbye, World!")
print(msg1) # Hello, World!
print(msg2) # Goodbye, World!
print(len(msg1)) # 13
print(msg1 + msg2) # Hello, World!Goodbye, World!
print(msg1 == msg2) # False
print(msg1 < msg2) # True
print(msg1 > msg2) # False
print("Hello" in msg1) # True
print(msg1[0]) # H
msg1[0] = "J"
print(msg1) # Jello, World!
del msg1[0]
print(msg1) # ello, World!
for char in msg1:
print(char)
reversed_msg1 = reversed(msg1)
print(reversed_msg1) # ,dlroW olle
reversed_msg1()
```
希望这个代码示例能够帮助你!
阅读全文