class X:
pass
class Y:
"""Class Y"""
def __str__(self):
return "{} object".format(self.__class__.__name__)
def __len__(self):
return 10
def __bool__(self):
return False
def check_bool(x):
if x:
print("I'm {}. My bool value is True.".format(str(x)))
else:
print("I'm {}. My bool value is False.".format(str(x)))
def main():
x = X()
y = Y()
print(x)
print(y)
# print(len(x))
print(len(y))
check_bool(x)
check_bool(y)
print(X.__doc__)
print(Y.__doc__)
if __name__ == "__main__":
main()
输出:
<__main__.X object at 0x103306e80>
Y object
10
I'm <__main__.X object at 0x103306e80>. My bool value is True.
I'm Y object. My bool value is False.
None
Class Y
1. 之所以要实现special method,是为了了让自自定义的class与Python的内置函数无无缝衔接
2. Python有大大量量的内置函数,而而这些函数大大部分都是调用用的对象里里里的special method
3. 想查看Python中到底有多少special method: