039_特殊方法(魔术方法).py

#-*- coding = utf-8 -*-
#@Time:2020/8/5 16:41
#@Author:huxuehao
#@File:039_特殊方法(魔术方法).py
#@Software:PyCharm
#@Theme:

# 特殊方法:
#     1.特殊方法是以“__”开头和结尾的
#     2.特殊方法一般不需要手动调用,会自动调用

# 1.__init__(self)  : 初始化方法,创建对象时,类后面的所有参数,都会一次传递到init中

# 2.__del__(self)  : 它会在对象被垃圾回收前自动执行

# 3.__str__(self)  : 打印对象名时,就会打印出 __str__(self) 中的返回值
class  Str:
    def __str__(self):
        return "打印 Str 的对象时,打印的是我的返回值"
s=Str()
print(s)
#或 print(str(s))
print(str(s))

print()
# 4.__repr__(self)  : 对当前对象适应repr函数时调用,
#                     他的作用是指定对象在 交互模式 中输出结果
class  Repr:
    def __repr__(self):
        return "打印 repr(对象名) 的对象时,打印的是我的返回值"
s=Repr()
print(repr(s))

# 5. 对象之间的比较运算符
# __lt__(self,other)  : <
# __le__(self,other)  : <=
# __eq__(self,other)  : ==
# __ne__(self,other)  : !=
# __gt__(self,other)  : >
# __ge__(self,other)  : >=
print()
# __gt__(self,other): 该方法会在对象做大小比较时调用,例如:print( obj1 > obj2 )
#                     他需要两个参数,self 相当于obj1, other 相当于obj2
class  Gt:
    def __init__(self,age):
        self._age=age

    def __gt__(self,other):
        return self._age > other._age
s1=Gt('18')
s2=Gt('15')
print(s1>s2)    # True

# 6.__len__(self)  : 获取去对象的长度

# 7.__bool__(self)  : 获取对象是否为空
#                   我们可以自定义 返值得条件。比如:可以判断一个人是否成年
print()
s3=Gt('1')
s4=Gt('2')
s4=None  # 此时对象为空
print(bool(s3)) # True
print(bool(s4)) # False

# 8.运算
# __add__(self,other)  +
# __sub__(self,other)  -
# __mul__(self,other)  *
# __matmul__(self,other)
# __truediv__(self,other)
# __floordiv__(self,other)
# __mod__(self,other)  %
# __divmod__(self,other)
# __pow__(self,other)
# __lshift__(self,other)
# __rshift__(self,other)
# __and__(self,other)  and
# __xor__(self,other)
# __or__(self,other)  or

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值