Last active
January 4, 2024 04:17
-
-
Save icecoobe/8a0973dc9756632da616818274bba5dc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/python | |
# Desc: Demostrate the usage of __str__ and __repr__ magic methods | |
""" Demostrate the usage of __str__ and __repr__ magic methods | |
""" | |
# class TestClass(object): | |
class TestClass(): | |
# 定义对象的初始化行为 | |
def __init__(self): | |
self.a = 1 | |
self.b =2 | |
# 返回对象的字符串表示的方法, 与format()配合使用 | |
def __str__(self): | |
return f"TestClass tostring: {self.a} {self.b}" | |
# 返回对象的规范字符串表示的方法, 与repr()配合使用 | |
def __repr__(self): | |
return f"TestClass(name='{self.a}' '{self.b}')" | |
# 定义对象被销毁时的行为 | |
def __del__(self): | |
print("obj deleted") | |
# 定义对象的长度,通常与内置函数 len() 配合使用 | |
def __len__(self): | |
return 2*3 | |
# 定义对象的可调用行为,使得对象可以像函数一样被调用 | |
def __call__(self): | |
print("obj call") | |
# 定义对象的hash值,通常与内置函数 hash() 配合使用 | |
def __hash__(self): | |
return self.a + self.b | |
if __name__ == "__main__": | |
t = TestClass() | |
print(t) | |
print(repr(t)) | |
print(f"{t}") | |
print(f"{repr(t)}") | |
print(f"{t!r}") | |
print(len(t)) | |
print(hash(t)) | |
t() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment