当前位置:   article > 正文

(Python高级编程)第二章:Python中的魔法函数_python魔法函数

python魔法函数

一:什么是魔法函数

(1)魔法函数

魔法函数:在Python中,魔法函数是以__开头和结尾的函数,例如下面Python中会内置很多的魔法函数

在这里插入图片描述

魔法函数是Python的一种高级语法,允许你在类中自定义函数,并绑定到类的特殊方法中。我们经常使用的构造函数__init__和析构函数__del__就属于魔法函数

(2)作用

魔法函数作用:类中的魔法函数继承自object类,其作用有点像Java中的重写(例如Java中我们经常会重写toString()方法)。接下来举两个例子帮助大家理解魔法函数的作用——让类具有一些额外的功能、方便使用者理解


①:如下有一个CompanyPeople类,用于描述一个公司的员工,构造函数参数处传入一个参数列表。接着实例化对象company_people

  • 如果需要遍历这个对象,那么在这种情况下就必须使用company_people.company_people_list,而不能直接是company_people
class CompanyPeople():
    def __init__(self, company_people_list):
        self.company_people_list = company_people_list

company_people = CompanyPeople(["张三", "李四", "王麻子"])

for people in company_people.company_people_list:
    print(people)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

在这里插入图片描述

所以为了让这种遍历显得更加直接,我们可以使用类中的一个魔法函数__getitem__,它会在对象被迭代时发挥作用。在被迭代时会传入当前的循环变量然后进行索引

  • 此时在进行遍历时可以直接写成company_people
class CompanyPeople():
    def __init__(self, company_people_list):
        self.company_people_list = company_people_list
    def __getitem__(self, item):
        return self.company_people_list[item]

company_people = CompanyPeople(["张三", "李四", "王麻子"])

for people in company_people:
    print(people)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

②:如下是一个People类,有agesalary两个属性,分别表示年龄和薪资。现在我们想要让一些人进行排序,排序就会涉及大小比较,而在正常情况下,人是不能直接比较大小的,所以必须要为其制定一定的规则。这时__gt__魔法函数就派上用场了,它表示greater than,所以在进行比较时,该函数就会自动被调用

class People():
    def __init__(self, age, salary):
        self.age = age
        self.salary = salary

    def __gt__(self, other):
        if self.age > other.age:
            return True
        else:
            if self.salary > other.salary:
                return True
            else:
                return False

people_list = [People(7, 50000)
               , People(27, 1300)
               , People(18, 898989)
               , People(18, 4000)
               , People(77, 23000)
               ]
people_list = sorted(people_list)

for i in people_list:
    print(i.age, i.salary)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24

二:Python中的魔法函数

Python中的魔法函数非常多,仅靠一篇文章不可能全部介绍完毕,而且很多魔法函数必须结合具体的例子学起来才有意义。所以这里重点介绍字符串表示集合序列相关魔法函数,剩余魔法函数在大家遇到此类问题时随时查阅学习即可

在这里插入图片描述

(1)字符串表示

①:__repr__:用于自定义输出实例化对象信息

  • 默认情况下(也即用户不显式写出__repr__方法时)会得到“类名+object at+内存地址”这样格式的信息
  • 当显示写出__repr__方法时,解释器会按照你所定义的格式输出实例对象信息
  • __repr__面向程序员
lass People1():
    pass

people1 = People1()
print(people1)  # 相当于执行了print(people1.repr())
print("-"*20)


class People2():
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __repr__(self):
        return "People2[name=" + self.name + ", age=" + str(self.age) + "]"

people2 = People2("张三", 27)
print(people2)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18

在这里插入图片描述

②:__str__:用于返回一个对象的描述信息

  • __str__面向用户
  • __repr__适用于所有环境中,__str__只是覆盖了__repr__以得到更友好的用户显示
  • __str__类似于Java中的toString()方法

class People():
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return "name:%s, age:%d" % (self.name, self.age)
        #或者
        return "name=" + self.name + ", age=" + str(self.age)

people = People("张三", 27)
print(people)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13

在这里插入图片描述

(2)集合序列相关

①:__len__:在Python中,我们经常会使用len()函数获取一个对象的长度,实际上在其内部会自动调用该对象的__len()__方法

class WordNums():
    def __init__(self, *args):
        self.word = args

    def __len__(self):
        print("调用了__len__方法")
        return len(self.word)

ret = WordNums('hello', 'world', 'Python', 'encoding')
print(len(ret))
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

在这里插入图片描述

②:__getitem__:在被迭代时会传入当前的循环变量然后进行索引

class CompanyPeople():
    def __init__(self, company_people_list):
        self.company_people_list = company_people_list
    def __getitem__(self, item):
        return self.company_people_list[item]

company_people = CompanyPeople(["张三", "李四", "王麻子"])

for people in company_people:
    print(people)
print(company_people[1])
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11

在这里插入图片描述

③:__ setitem__: 这个方法应该以与键相关联的方式(类似字典的方式)存储值,以便之后能够使用__setitem__来获取(也即key/value

class Test:
    def __init__(self):
        self.dicts = {'a':'A', 'b':'B', 'c':'D'}

    def __getitem__(self, item):
        return self.dicts[item]

    def __setitem__(self, key, value):
        print("调用__setitem")
        self.dicts[key] = value

test = Test();
print("test[a]=" + test['a'])
print("test[b]=" + test['b'])
print("test[c]=" + test['c'])
print("-"*20)

test['c'] = 'C'
print("test[c]=" + test['c'])
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19

在这里插入图片描述

④:__ delitem__: 此方法在对象组成部分(对象必须可变)使用del语句时被调用,会删除与key相关联的值

class Test:
    def __init__(self):
        self.dicts = {'a':'A', 'b':'B', 'c':'D'}

    def __getitem__(self, item):
        return self.dicts[item]

    def __setitem__(self, key, value):
        print("调用__setitem")
        self.dicts[key] = value

    def __delitem__(self, key):
        print("调用__delitem")
        del self.dicts[key]

test = Test();
print(test.dicts)
print("-"*20)

del test['c']
print(test.dicts)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

在这里插入图片描述

⑤:__ contains__: 用于判断我们输入的数据是否在类里

class Test:
    def __init__(self):
        self.lists = [111, 222, 333, 999]
    def __getitem__(self, item):
        return self.lists[item]

    def __contains__(self, item):
        return item in self.lists


test = Test()
print(test.lists)
print(444 in test.lists)
print(999 in test.lists)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

在这里插入图片描述

(3)迭代相关-

  • __iter__
  • __next__

(4)可调用

  • _call_

(5)with上下文管理器

  • __enter__
  • __exit__

(6)数制转换

  • __abs__
  • __bool__
  • __int__
  • __float__
  • __hash__
  • __index__

(7)元类相关

  • __new__
  • __init__

(8)属性相关

  • __getattr____setattr__
  • __getattribute____setattribute__
  • __dir__

(9)属性描述符

  • __get__
  • __set__
  • __delete__

(10)协程

  • __await__
  • __aiter__
  • __anext__
  • __aenter__
  • __aexit__

(11)数学运算类

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/爱喝兽奶帝天荒/article/detail/756653
推荐阅读
相关标签
  

闽ICP备14008679号