python : special method

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:

https://rszalski.github.io/magicmethods/

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值