python常见的魔术方法

什么是魔术方法

Python类的内置方法,各自有各自的特殊功能,被称之为魔术方法

常见的魔术方法有以下:

python 复制代码
__init__:构造方法
__str__:字符串方法
__lt__:小于、大于符号比较
__le__:小于等于、大于等于符合比较
__eq__:等于符合比较

__init__

python 复制代码
class Student:
    def __init__(self,name,age):
        self.name = name
        self.age = age

负责创建对象时初始化对象,给成员变量赋值初始值

调用:

python 复制代码
if __name__ == '__main__':
    stu = Student('yohoo', 27)
    print(stu.name)
    print(stu.age)

结果:

__str__

如果没有__str__方法,打印类的对象是内存地址

python 复制代码
if __name__ == '__main__':
    stu = Student('yohoo', 27)
    print(stu)
    print(str(stu))

结果:

当添加__str__方法

整体代码:

python 复制代码
class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return "我是%s,我的年龄是%d" % (self.name, self.age)


if __name__ == '__main__':
    stu = Student('yohoo', 27)
    print(stu)
    print(str(stu))

结果:

__lt__

如果没有__lt__不能直接对两个对象进行小于大于的比较

如果添加此魔术方法,other参数表示的另一个对象

python 复制代码
class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __lt__(self, other):
        return self.age < other.age

if __name__ == '__main__':
    stu1 = Student('yohoo', 27)
    stu2 = Student('zz', 29)
    print(stu1 < stu2)
    print(stu1 > stu2)

结果:

____le__

与上面__lt__类似,le是针对小于等于或者大于等于

python 复制代码
class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __le__(self, other):
        return self.age <= other.age

if __name__ == '__main__':
    stu1 = Student('yohoo', 27)
    stu2 = Student('zz', 29)
    print(stu1 <= stu2)
    print(stu1 >= stu2)

结果:

__eq__

和上面类似,eq是针对等于

python 复制代码
class Student:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __eq__(self, other):
        return self.age == other.age

if __name__ == '__main__':
    stu1 = Student('yohoo', 29)
    stu2 = Student('zz', 29)
    print(stu1 == stu2)

结果:

相关推荐
T - mars2 分钟前
python爬虫:喜马拉雅案例(破解sign值)
javascript·爬虫·python
Loving_enjoy13 分钟前
从响应式编程到未来架构革命:解锁高并发时代的底层思维范式
python·ai编程
北京_宏哥33 分钟前
🔥PC端自动化测试实战教程-2-pywinauto 启动PC端应用程序 - 上篇(详细教程)
前端·windows·python
_x_w42 分钟前
【12】数据结构之基于线性表的排序算法
开发语言·数据结构·笔记·python·算法·链表·排序算法
北京_宏哥44 分钟前
🔥PC端自动化测试实战教程-1-pywinauto 环境搭建(详细教程)
前端·windows·python
grrrr_11 小时前
【ctfplus】python靶场记录-任意文件读取+tornado模板注入+yaml反序列化(新手向)
python·web安全·tornado
ππ记录1 小时前
python面试技巧
python·python面试·python面试技巧·python面试能力
csdn_aspnet2 小时前
windows 安装 pygame( pycharm)
python·pycharm·pygame
这里有鱼汤2 小时前
Python自动化神器Playwright:让浏览器乖乖听话的终极指南!
后端·爬虫·python
海天一色y2 小时前
Pycharm(十三)容器类型的公共运算符和公共方法
ide·python·pycharm