脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - Python类的高级函数详解

Python类的高级函数详解

2021-12-21 12:55Insane_Loafer Python

这篇文章主要介绍了Python类的高级函数,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下

__str__函数

  • 如果定义了该函数,当print当前实例化对象的时候,会返回该函数的return信息
  • 可用于定义当前类的描述信息
  • 用法:
?
1
2
def __str__(self):
    return str_type
  • 参数:无
  • 返回值:一般返回对于该类的描述信息

Python类的高级函数详解

__getattr__函数

  • 当调用的属性或者方法不存在时,会返回该方法定义的信息
  • 用法:
?
1
2
def __getattr__(self, key):
    print(something.….)
  • 参数:

key: 调用任意不存在的属性名

  • 返回值:

可以是任意类型也可以不进行返回

Python类的高级函数详解

__setattr__函数

  • 拦截当前类中不存在的属性与值
  • 用法:
?
1
2
def __settattr__(self, key,value):
    self._dict_[key] = value
  • 参数:

key当前的属性名

value 当前的参数对应的值

  • 返回值: 无

Python类的高级函数详解

__call__函数

  • 本质是将一个类变成一个函数
  • 用法:
?
1
2
def __call__(self,*args,**kwargs):
    print( 'call will start')
  • 参数: 可传任意参数
  • 返回值: 与函数情况相同可有可无

Python类的高级函数详解

实战

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# @time     : 2021/8/15 18:22
# @author   : insaneloafer
# @file     : object_func.py
 
class test(object):
 
    def __str__(self):
        return 'this is a test class'
 
    def __getattr__(self, key):
        return '这个key:{}并不存在'.format(key)
 
    def __setattr__(self, key, value):
        print(key, value)
        self.__dict__[key] = value
        print(self.__dict__)
 
    def __call__(self, *args, **kwargs):
        print('call will start')
        print(args, kwargs)
 
t = test()
print(t)
print(t.a)  # 不存在的对象会直接打印出来,而不是报错
t.name = 'insane'
t(123, name='loafer')
 
 
"""实现链式操作"""
class test2(object):
    def __init__(self, attr=''):
        self.__attr = attr
 
    def __call__(self, name):
        print('key is {}'.format(self.__attr))
        return name
 
    def __getattr__(self, key):
        if self.__attr:
            key = '{}.{}'.format(self.__attr, key)
        else:
            key = key
        print(key)
        return test2(key)  # 递归操作
 
t2 = test2()
print(t2.a.c('insane'))
?
1
2
3
4
5
6
7
8
9
10
11
12
this is a test class
这个key:a并不存在
name insane
{'name': 'insane'}
call will start
(123,) {'name': 'loafer'}
a
a.c
key is a.c
insane
 
process finished with exit code 0

到此这篇关于python类的高级函数的文章就介绍到这了,更多相关python高级函数内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!

原文链接:https://blog.csdn.net/m0_48978908/article/details/119717505

延伸 · 阅读

精彩推荐