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)

结果:

相关推荐
子夜江寒11 分钟前
基于 OpenCV 的图像形态学与边缘检测
python·opencv·计算机视觉
少林码僧7 小时前
2.31 机器学习神器项目实战:如何在真实项目中应用XGBoost等算法
人工智能·python·算法·机器学习·ai·数据挖掘
智航GIS7 小时前
10.4 Selenium:Web 自动化测试框架
前端·python·selenium·测试工具
jarreyer7 小时前
摄像头相关记录
python
宝贝儿好7 小时前
【强化学习】第六章:无模型控制:在轨MC控制、在轨时序差分学习(Sarsa)、离轨学习(Q-learning)
人工智能·python·深度学习·学习·机器学习·机器人
大、男人7 小时前
python之asynccontextmanager学习
开发语言·python·学习
默默前行的虫虫8 小时前
nicegui文件上传归纳
python
一个没有本领的人8 小时前
UIU-Net运行记录
python
国强_dev8 小时前
Python 的“非直接原因”报错
开发语言·python
副露のmagic9 小时前
更弱智的算法学习 day24
python·学习·算法