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)

结果:

相关推荐
星期天要睡觉14 分钟前
深度学习——循环神经网络(RNN)
人工智能·python·rnn·深度学习·神经网络
Blossom.11835 分钟前
把AI“撒”进农田:基于极值量化与状态机的1KB边缘灌溉决策树
人工智能·python·深度学习·算法·目标检测·决策树·机器学习
Red Car35 分钟前
如何向文件夹内所有PDF增加水印
python·pdf
Q_Q5110082851 小时前
python+uniapp基于微信小程序团购系统
spring boot·python·微信小程序·django·uni-app·node.js·php
java1234_小锋1 小时前
TensorFlow2 Python深度学习 - 循环神经网络(LSTM)示例
python·rnn·深度学习·tensorflow2
测试老哥2 小时前
Postman环境变量设置全攻略
自动化测试·软件测试·python·测试工具·职场和发展·接口测试·postman
惜月_treasure2 小时前
Text2SQL与工作流实现:让数据库查询变得轻松又高效
数据库·人工智能·python
码猩3 小时前
获取dm音视频文案
python
给我起把狙3 小时前
Django与Tornado框架深度对比:从MVCMTV到高并发架构设计
python·django·tornado
Hello.Reader3 小时前
Flink DataStream「全分区窗口处理」mapPartition / sortPartition / aggregate / reduce
大数据·python·flink