【Python】我所知道的内置函数(二)

108 阅读4分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第17天,点击查看活动详情


这一篇承接上一篇:【Python】我所知道的内置函数(一)

四 内置函数讲解(二)

注意⚠️: 当前操作实验环境为 MacOS Monterey 12.6Python 3.10.1 不同的分类或者叫法不一致,这个请酌情参考。其他版本略有更改,请留意。

5 反射操作

import:动态导入模块

index = __import__('index')
index.sayHello()

isinstance:判断对象是否是类或者类型元组中任意类元素的实例

>>> isinstance(1,int)
True
>>> isinstance(1,str)
False
>>> isinstance(1,(int,str))
True

issubclass:判断类是否是另外一个类或者类型元组中任意类元素的子类

>>> issubclass(bool,int)
True
>>> issubclass(bool,str)
False
 
>>> issubclass(bool,(str,int))
True

hasattr:检查对象是否含有属性

#定义类A
>>> class Student:
    def __init__(self,name):
        self.name = name
 
        
>>> s = Student('Aim')
>>> hasattr(s,'name') #a含有name属性
True
>>> hasattr(s,'age') #a不含有age属性
False

getattr:获取对象的属性值

#定义类Student
>>> class Student:
    def __init__(self,name):
        self.name = name
 
>>> getattr(s,'name') #存在属性name
'Aim'
 
>>> getattr(s,'age',6) #不存在属性age,但提供了默认值,返回默认值
 
>>> getattr(s,'age') #不存在属性age,未提供默认值,调用报错
Traceback (most recent call last):
  File "<pyshell#17>", line 1, in <module>
    getattr(s,'age')
AttributeError: 'Stduent' object has no attribute 'age'

setattr:设置对象的属性值

>>> class Student:
    def __init__(self,name):
        self.name = name
 
        
>>> a = Student('Kim')
>>> a.name
'Kim'
>>> setattr(a,'name','Bob')
>>> a.name
'Bob'

delattr:删除对象的属性

#定义类A
>>> class A:
    def __init__(self,name):
        self.name = name
    def sayHello(self):
        print('hello',self.name)
 
#测试属性和方法
>>> a.name
'小麦'
>>> a.sayHello()
hello 小麦
 
#删除属性
>>> delattr(a,'name')
>>> a.name
Traceback (most recent call last):
  File "<pyshell#47>", line 1, in <module>
    a.name
AttributeError: 'A' object has no attribute 'name'

callable:检测对象是否可被调用

>>> class B: #定义类B
    def __call__(self):
        print('instances are callable now.')
 
        
>>> callable(B) #类B是可调用对象
True
>>> b = B() #调用类B
>>> callable(b) #实例b是可调用对象
True
>>> b() #调用实例b成功
instances are callable now.

6 变量操作

globals:返回当前作用域内的全局变量和其值组成的字典

>>> globals()
{'__spec__': None, '__package__': None, '__builtins__': <module 'builtins' (built-in)>, '__name__': '__main__', '__doc__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>}
>>> a = 1
>>> globals() #多了一个a
{'__spec__': None, '__package__': None, '__builtins__': <module 'builtins' (built-in)>, 'a': 1, '__name__': '__main__', '__doc__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>}

locals:返回当前作用域内的局部变量和其值组成的字典

>>> def f():
    print('before define a ')
    print(locals()) #作用域内无变量
    a = 1
    print('after define a')
    print(locals()) #作用域内有一个a变量,值为1
    
>>> f
<function f at 0x03D40588>
>>> f()
before define a 
{} 
after define a
{'a': 1}

7 交互操作

print:向标准输出对象打印输出

>>> print(1,2,3)
1 2 3
>>> print(1,2,3,sep = '+')
1+2+3
>>> print(1,2,3,sep = '+',end = '=?')
1+2+3=?

input:读取用户输入值

>>> s = input('please input your name:')
please input your name:Ain
>>> s
'Ain'

8 文件操作

open:使用指定的模式和编码打开文件,返回文件读写对象

# t为文本读写,b为二进制读写
>>> a = open('test.txt','rt')
>>> a.read()
'some text'
>>> a.close()

9 编译执行

compile:将字符串编译为代码或者AST对象,使之能够通过exec语句来执行或者eval进行求值

>>> #流程语句使用exec
>>> code1 = 'for i in range(0,10): print (i)'
>>> compile1 = compile(code1,'','exec')
>>> exec (compile1)
0
1
2
3
4
5
6
7
8
9
 
 
>>> #简单求值表达式用eval
>>> code2 = '1 + 2 + 3 + 4'
>>> compile2 = compile(code2,'','eval')
>>> eval(compile2)
10

eval:执行动态表达式求值

>>> eval('1+2+3+4')
10

exec:执行动态语句块

>>> exec('a=1+2') #执行语句
>>> a
3

repr:返回一个对象的字符串表现形式(给解释器)

>>> a = 'some text'
>>> str(a)
'some text'
>>> repr(a)
"'some text'"

10 装饰器

property:标示属性的装饰器

>>> class C:
    def __init__(self):
        self._name = ''
    @property
    def name(self):
        """i'm the 'name' property."""
        return self._name
    @name.setter
    def name(self,value):
        if value is None:
            raise RuntimeError('name can not be None')
        else:
            self._name = value
 
            
>>> c = C()
 
>>> c.name # 访问属性
''
>>> c.name = None # 设置属性时进行验证
Traceback (most recent call last):
  File "<pyshell#84>", line 1, in <module>
    c.name = None
  File "<pyshell#81>", line 11, in name
    raise RuntimeError('name can not be None')
RuntimeError: name can not be None
 
>>> c.name = 'Kim' # 设置属性
>>> c.name # 访问属性
'Kim'
 
>>> del c.name # 删除属性,不提供deleter则不能删除
Traceback (most recent call last):
  File "<pyshell#87>", line 1, in <module>
    del c.name
AttributeError: can't delete attribute
>>> c.name
'Kim'

classmethod:标示方法为类方法的装饰器

>>> class C:
    @classmethod
    def f(cls,arg1):
        print(cls)
        print(arg1)
 
        
>>> C.f('类对象调用类方法')
<class '__main__.C'>
类对象调用类方法
 
>>> c = C()
>>> c.f('类实例对象调用类方法')
<class '__main__.C'>
类实例对象调用类方法

staticmethod:标示方法为静态方法的装饰器

# 使用装饰器定义静态方法
>>> class Student(object):
    def __init__(self,name):
        self.name = name
    @staticmethod
    def sayHello(lang):
        print(lang)
        if lang == 'en':
            print('Welcome!')
        else:
            print('你好!')
 
            
>>> Student.sayHello('en') #类调用,'en'传给了lang参数
en
Welcome!
 
>>> b = Student('Kim')
>>> b.sayHello('zh')  #类实例对象调用,'zh'传给了lang参数
zh
你好

总结(二)

内置函数简单、简洁,学习内置函数不需要花费太大的成本,但是需要我们拥有记忆来记住这些常用的内置函数,极大的提升了程序员的效率和程序的阅读。

参考

参考文献:

[1]内置函数:baike.baidu.com/item/%E5%86…

[2]Python 3.10官方文档:docs.python.org/3.10/

[3]Python 3.10 官方内置函数说明文档:docs.python.org/zh-cn/3/lib…