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)

结果:

相关推荐
MediaTea5 分钟前
Jupyter Notebook:基于 Web 的交互式编程环境
前端·ide·人工智能·python·jupyter
阿_旭6 分钟前
基于深度学习的CT扫描图像肝脏肿瘤智能检测与分析系统【python源码+Pyqt5界面+数据集+训练代码】
人工智能·python·深度学习·肝脏肿瘤分割
belldeep1 小时前
python:Django 和 Vue.js 技术栈解析
vue.js·python·django
蓝桉~MLGT1 小时前
Python学习历程——基础语法(print打印、变量、运算)
开发语言·python·学习
小熊出擊2 小时前
[pytest] autouse 参数:自动使用fixture
python·测试工具·单元测试·自动化·pytest
诗句藏于尽头2 小时前
关于七牛云OSS存储的图片数据批量下载到本地
开发语言·windows·python
2401_841495643 小时前
【计算机视觉】图像去雾技术
人工智能·python·opencv·算法·计算机视觉·技术·图像去雾
在钱塘江3 小时前
Elasticsearch 快速入门 - Python版本
后端·python·elasticsearch
王彦臻3 小时前
PyTorch 中模型测试与全局平均池化的应用总结
人工智能·pytorch·python
_码力全开_4 小时前
Python从入门到实战 (14):工具落地:用 PyInstaller 打包 Python 脚本为可执行文件
开发语言·数据结构·python·个人开发