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)

结果:

相关推荐
久绊A2 小时前
Python 基本语法的详细解释
开发语言·windows·python
Hylan_J5 小时前
【VSCode】MicroPython环境配置
ide·vscode·python·编辑器
莫忘初心丶5 小时前
在 Ubuntu 22 上使用 Gunicorn 启动 Flask 应用程序
python·ubuntu·flask·gunicorn
失败尽常态5238 小时前
用Python实现Excel数据同步到飞书文档
python·excel·飞书
2501_904447748 小时前
OPPO发布新型折叠屏手机 起售价8999
python·智能手机·django·virtualenv·pygame
青龙小码农8 小时前
yum报错:bash: /usr/bin/yum: /usr/bin/python: 坏的解释器:没有那个文件或目录
开发语言·python·bash·liunx
大数据追光猿8 小时前
Python应用算法之贪心算法理解和实践
大数据·开发语言·人工智能·python·深度学习·算法·贪心算法
Leuanghing9 小时前
【Leetcode】11. 盛最多水的容器
python·算法·leetcode
xinxiyinhe10 小时前
如何设置Cursor中.cursorrules文件
人工智能·python
诸神缄默不语10 小时前
如何用Python 3自动打开exe程序
python·os·subprocess·python 3