wordpress 网站标题设置方法,石油大学 网页设计与网站建设,青岛市网页设计公司,淮安市淮阴区建设局网站什么是魔术方法
Python类的内置方法#xff0c;各自有各自的特殊功能#xff0c;被称之为魔术方法
常见的魔术方法有以下#xff1a;
__init__:构造方法
__str__:字符串方法
__lt__:小于、大于符号比较
__le__:小于等于、大于等于符合比较
__eq__:等于符合比较__init__ c…什么是魔术方法
Python类的内置方法各自有各自的特殊功能被称之为魔术方法
常见的魔术方法有以下
__init__:构造方法
__str__:字符串方法
__lt__:小于、大于符号比较
__le__:小于等于、大于等于符合比较
__eq__:等于符合比较__init__ class Student:def __init__(self,name,age):self.name nameself.age age负责创建对象时初始化对象给成员变量赋值初始值
调用
if __name__ __main__:stu Student(yohoo, 27)print(stu.name)print(stu.age)结果 __str__ 如果没有__str__方法打印类的对象是内存地址
if __name__ __main__:stu Student(yohoo, 27)print(stu)print(str(stu))结果 当添加__str__方法
整体代码
class Student:def __init__(self, name, age):self.name nameself.age agedef __str__(self):return 我是%s,我的年龄是%d % (self.name, self.age)if __name__ __main__:stu Student(yohoo, 27)print(stu)print(str(stu))结果 __lt__ 如果没有__lt__不能直接对两个对象进行小于大于的比较 如果添加此魔术方法other参数表示的另一个对象
class Student:def __init__(self, name, age):self.name nameself.age agedef __lt__(self, other):return self.age other.ageif __name__ __main__:stu1 Student(yohoo, 27)stu2 Student(zz, 29)print(stu1 stu2)print(stu1 stu2)结果 ____le__ 与上面__lt__类似le是针对小于等于或者大于等于
class Student:def __init__(self, name, age):self.name nameself.age agedef __le__(self, other):return self.age other.ageif __name__ __main__:stu1 Student(yohoo, 27)stu2 Student(zz, 29)print(stu1 stu2)print(stu1 stu2)
结果 __eq__ 和上面类似eq是针对等于
class Student:def __init__(self, name, age):self.name nameself.age agedef __eq__(self, other):return self.age other.ageif __name__ __main__:stu1 Student(yohoo, 29)stu2 Student(zz, 29)print(stu1 stu2)结果