S1.5 魔术方法

上一节中我们学习的__init__构造方法,是Python类内置的方法之一。

这些内置的类方法,各自有各自特殊的功能,这些内置方法我们便称之为:魔术方法

Python当中有很多魔术方法,本篇中只讲解几种常用的。

__str__字符串方法

当我们尝试直接print某个对象时,例如:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
class db:
    def __init__(self,host,uid,pwd):
        self.host = host
        self.uid = uid
        self.pwd = pwd


data1 = db('192.168.0.1','root','toor')

print(data1)		# 输出 <__main__.db object at 0x000001EECBC68AD0>
print(str(data1)) 	# 输出 <__main__.db object at 0x000001EECBC68AD0>

很显然,这并不是我们想要的,所以我们可以使用__str__方法

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class db:
    def __init__(self,host,uid,pwd):
        self.host = host
        self.uid = uid
        self.pwd = pwd
    def __str__(self):
        return f"db类对象,host:{self.host},uid:{self.uid},pwd:{self.pwd}"

data1 = db('192.168.0.1','root','toor')

print(data1)		# 输出 db类对象,host:192.168.0.1,uid:root,pwd:toor
print(str(data1)) 	# 输出 db类对象,host:192.168.0.1,uid:root,pwd:toor

很显然,我们可以由此看出,__str__方法的功能就是自定义print某个对象时输出的语句模板。

__lt__小于符号比较方法

当我们想要对两个对象进行比较(期望输出True或Flase)时会报错,例如:

1
2
3
4
5
6
7
8
9
class Student:
    def __init__(self,name,age,gender):
        self.name = name
        self.age = age
        self.gender = gender
stu1 = Student('小明',18,'男')
stu2 = Student('小花',22,'女')
print(stu1 > stu2)
print(stu1 < stu2)

但是如果使用__lt__方法,即可同时完成: 小于符号大于符号 2种比较

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Student:
    def __init__(self,name,age,gender):
        self.name = name
        self.age = age
        self.gender = gender

    def __lt__(self,other):
        return self.age < other.age		# 此处other指另外一个类对象,为固定写法
stu1 = Student('小明',18,'男')
stu2 = Student('小花',22,'女')
print(stu1 > stu2)	# 输出Flase
print(stu1 < stu2)	# 输出True

__le__小于等于比较符号方法

跟上面的__lt__方法相似,只不过__le__可以用于小于等于和大于等于的比较,所以简单替换一下就行。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
class Student:
    def __init__(self,name,age,gender):
        self.name = name
        self.age = age
        self.gender = gender

    def __le__(self,other):
        return self.age <= other.age		# 此处other指另外一个类对象,为固定写法
stu1 = Student('小明',18,'男')
stu2 = Student('小花',22,'女')
print(stu1 >= stu2)	# 输出Flase
print(stu1 <= stu2)	# 输出True

__eq__比较运算符实现方法

__eq__也是一样,是用来判断某两个类之间的相等关系,把运算符号换乘等号就行。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
class Student:
    def __init__(self,name,age,gender):
        self.name = name
        self.age = age
        self.gender = gender

    def __eq__(self,other):
        return self.age == other.age		# 此处other指另外一个类对象,为固定写法
stu1 = Student('小明',18,'男')
stu2 = Student('小花',22,'女')
stu3 = Student('小王',18,'男')
print(stu1 == stu2)	# 输出Flase
print(stu1 == stu3) # 输出True
Licensed under CC BY-NC-SA 4.0
已存在于互联网
发表了126篇文章 · 总计210.25k字
萌ICP备20267077号
Powered by ctOS