python3 内置函数06

1 classmethod 修饰符对应的函数不需要实例化,不需要 self 参数,但第一个参数需要是表示自身类的 cls 参数,可以来调用类的属性,类的方法,实例化对象等。

class A(object):
    bar = 1
    def func1(self):  
        print ('foo') 
    @classmethod
    def func2(cls):
        print ('func2')
        print (cls.bar)
        cls().func1()   # 调用 foo 方法
 
A.func2()               # 不需要实例化
#func2
#1
#foo

2 getattr() 函数用于返回一个对象属性值。

>>>class A(object):
...     bar = 1
... 
>>> a = A()
>>> getattr(a, 'bar')        # 获取属性 bar 值
1
>>> getattr(a, 'bar2')       # 属性 bar2 不存在,触发异常
Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'A' object has no attribute 'bar2'
>>> getattr(a, 'bar2', 3)    # 属性 bar2 不存在,但设置了默认值
3

3 locals() 函数会以字典类型返回当前位置的全部局部变量。

>>>def runoob(arg):    # 两个局部变量:arg、z
...     z = 1
...     print (locals())
... 
>>> runoob(4)
{'z': 1, 'arg': 4}      # 返回一个名字/值对的字典

4 repr() 函数将对象转化为供解释器读取的形式。

>>>s = 'RUNOOB'
>>> repr(s)
"'RUNOOB'"
>>> dict = {'runoob': 'runoob.com', 'google': 'google.com'};
>>> repr(dict)
"{'google': 'google.com', 'runoob': 'runoob.com'}"

5 zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象,这样做的好处是节约了不少的内存。

>>>a = [1,2,3]
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b)     # 返回一个对象
>>> zipped

>>> list(zipped)  # list() 转换为列表
[(1, 4), (2, 5), (3, 6)]
>>> list(zip(a,c))              # 元素个数与最短的列表一致
[(1, 4), (2, 5), (3, 6)]
 
>>> a1, a2 = zip(*zip(a,b))          # 与 zip 相反,*zip 可理解为解压,返回二维矩阵式
>>> list(a1)
[1, 2, 3]
>>> list(a2)
[4, 5, 6]

6 compile() 函数将一个字符串编译为字节代码。

>>>str = "for i in range(0,10): print(i)" 
>>> c = compile(str,'','exec')   # 编译为字节代码对象 
>>> c
 at 0x10141e0b0, file "", line 1>
>>> exec(c)
0
1
2
3
4
5
6
7
8
9
>>> str = "3 * 4 + 5"
>>> a = compile(str,'','eval')
>>> eval(a)
17

7 globals() 函数会以字典类型返回当前位置的全部全局变量。

>>>a='runoob'
>>> print(globals()) # globals 函数返回一个全局变量的字典,包括所有导入的变量。
{'__builtins__': , '__name__': '__main__',
 '__doc__': None, 'a': 'runoob', '__package__': None}

8 map() 会根据提供的函数对指定序列做映射。

>>>def square(x) :            # 计算平方数
...     return x ** 2
... 
>>> map(square, [1,2,3,4,5])   # 计算列表各个元素的平方
[1, 4, 9, 16, 25]
>>> map(lambda x: x ** 2, [1, 2, 3, 4, 5])  # 使用 lambda 匿名函数
[1, 4, 9, 16, 25]
 
# 提供了两个列表,对相同位置的列表数据进行相加
>>> map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10])
[3, 7, 11, 15, 19]

9 reversed 函数返回一个反转的迭代器。

# 列表
seqList = [1, 2, 4, 3, 5]
print(list(reversed(seqList)))

# [5, 3, 4, 2, 1]

10 import() 函数用于动态加载类和函数 。

如果一个模块经常变化就可以使用 import() 来动态载入。

import os  
 
print ('在 a.py 文件中 %s' % id(os))

test.py 文件代码:
import sys  
__import__('a')        # 导入 a.py 模块

# 执行结果
# 在 a.py 文件中 4394716136

你可能感兴趣的:(python3 内置函数06)