特殊方法

一、特殊方法(魔术方法)
- 特殊方法都是使用__开头和结尾的
- 特殊方法一般不需要手动调用,需要在一些特殊情况下自动执行
1、str()
(1)这个特殊方法会在尝试将对象转换为字符的时候调用
(2)它的作用可以用来指定对象转换为字符串的结果(print函数)
2、repr()
(1)这个特殊方法会在对当前对象使用repr()函数时调用
(2)它的作用是指定对象在 ‘ 交互模式 ’ 中直接输出的结果
3、 object.gt(self,other) 大于
(1)会在对象做大于比较的时候调用,该方法的返回值将会作为比较的结果
(2)它需要两个参数,一个self表示当前队形,other表示和当前对象比较的对象
(3)self > other
4、object.bool(self)
(1)可以通过bool来指定对象转换为布尔值的情况

  • 其他:
    object.it(self,other) 小于 <
    object.le(self,other) 小于等于 <=
    object.eq(self,other) 等于 ==
    object.ne(self,other) 不等于 !=
    object.ge(self,other) 大于等于 >=
    object.add(self,other)
    object.sub(self,other)
    object.mul(self,other)
    object.matmul(self,other)
    object.truediv(self,other)
    object.floordiv(self,other)
    object.mod(self,other)
    object.divmod(self,other)
    object.pow(self,other)
    object.Ishift(self,other)
    object.rshift(self,other)
    object.and(self,other)
    object.xor(self,other)
    object.or(self,other)

len()获取对象的长度

# 定义一个Person类
class Person(object):
    ''''人类''''
    def __init__(self,name,age):
        self.name = name
        self.age = age

    def __str__(self):
        return 'Person [name= %s,age=%d]'%(self.name,self.age)
    
    def __repr__(self):
        return 'Hello'
    
    def __gt__(self,other):
        return self.age > other.age
        
# 创建两个Person类的实例
p1 = Person('肖战'28)
p2 = Person('王一博'23)

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值