#查看内置函数
dir(__builtins__)
###########################################################################################################
# abs()函数返回数字的绝对值。
>>> abs(-40.00)
40.0
# max()方法返回给定参数的最大值,参数可以为序列。
>>> max(80,100,1000)
1000
# min()方法返回给定参数的最小值,参数可以为序列。
>>> min(80,100,1000)
80
# pow()方法返回x的y次方的值。
>>> pow(100,2)
10000
>>> import math
>>> math.pow(100,2)
10000.0
# round()方法返回浮点数x的四舍五入值。
>>> round(80.264,2)
80.26
###########################################################################################################
# chr()用一个整数作参数,返回一个对应的字符。
>>> print(chr(72),chr(101),chr(108),chr(108),chr(111))
H e l l o
# ord()函数是chr()函数的配对函数,它以一个字符串(Unicode字符)作为参数,返回对应的ASCII数值,或者Unicode数值。
>>> print(ord('A'),ord('Z'),ord('a'),ord('z'))
65 90 97 122
###########################################################################################################
# all() 函数用于判断给定的可迭代参数 iterable 中的所有元素是否都为 TRUE,如果是返回 True,否则返回 False。
print(all(['a', 'b', 'c', 'd']))# 列表list,元素都不为空或0
print(all(['a', 'b', '', 'd']))# 列表list,存在一个为空的元素
print(all([0, 1,2, 3]))# 列表list,存在一个为0的元素
print(all(('a', 'b', 'c', 'd'))) # 元组tuple,元素都不为空或0
print(all(('a', 'b', '', 'd'))) # 元组tuple,存在一个为空的元素
print(all((0, 1, 2, 3)))# 元组tuple,存在一个为0的元素
print(all([]))# 空列表 print()
print(all(()))# 空元组
# any() 函数用于判断给定的可迭代参数 iterable 是否全部为 False,则返回 False,如果有一个为 True,则返回 True。
print(any(['a', 'b', 'c', 'd'])) # 列表list,元素都不为空或0
print(any(['a', 'b', '', 'd']))# 列表list,存在一个为空的元素
print(any([0, '', False]))# 列表list,元素全为0,'',false
print(any(('a', 'b', 'c', 'd')))# 元组tuple,元素都不为空或0
print(any(('a', 'b', '', 'd')))# 元组tuple,存在一个为空的元素
print(any((0, '', False)))# 元组tuple,元素全为0,'',false
print(any([]))# 空列表
print(any(()))# 空元组
# ascii() 函数类似 repr() 函数, 返回一个表示对象的字符串
print(ascii("Hello World"))
# bin() 返回一个整数 int 或者长整数 long int 的二进制表示。
print(bin(10))
print(bin(20))
# bool() 函数用于将给定参数转换为布尔类型,如果没有参数,返回 False。
# bool 是 int 的子类。
print(bool())
print(bool(0))
print(bool(1))
print(issubclass(bool,int))
# bytearray() 方法返回一个新字节数组。这个数组里的元素是可变的,并且每个元素的值范围: 0 <= x < 256。
# class bytearray([source[, encoding[, errors]]])
print(bytearray())# bytearray(b'')
print(bytearray([1,2,3]))# bytearray(b'\x01\x02\x03')
print(bytearray("Hello World","utf-8")) # bytearray()
# bytes 函数返回一个新的 bytes 对象,该对象是一个 0 <= x < 256 区间内的整数不可变序列。它是 bytearray 的不可变版本。
# class bytes([source[, encoding[, errors]]])
a = bytes([1,2,3,4])
print(a)
print(type(a))
a = bytes('hello','ascii')
print(a)
print(type(a))
# callable() 函数用于检查一个对象是否是可调用的。
print(callable(0))
print(callable("Hello World"))
def add(q,b):
return a + b
print(callable(add)) # 函数返回 True
class A:
def method(self):
return 0
print(callable(A)) # 类返回 True
a = A()
print(callable(a)) # 没有实现 __call__, 返回 False
class B:
def __call__(self, *args, **kwargs):
return 0
b=B()
print(callable(b)) # 实现 __call__, 返回 True
# classmethod 修饰符对应的函数不需要实例化,不需要 self 参数,但第一个参数需要是表示自身类的 cls 参数,可以来调用类的属性,类的方法,实例化对象等。
class A(object):
bar=1
def func(self):
print('foo')
@classmethod
def fun2(cls):
print('fun2')
print(cls.bar)
cls().func()
A.fun2()
# compile() 函数将一个字符串编译为字节代码。
str="for i in range(0,10):print(i)"
c=compile(str,'','exec') # 编译为字节代码对象
print(c)
print(exec(c))
# delattr 函数用于删除属性。delattr(x, 'foobar') 相等于 del x.foobar。
class Coordinate:
x = 10
y = -5
z = 0
point1 = Coordinate()
print('x = ',point1.x)
print('y = ',point1.y)
print('z = ',point1.z)
delattr(Coordinate, 'z')
print('--删除 z 属性后--')
print('x = ',point1.x)
print('y = ',point1.y)
# 触发错误
print('z = ',point1.z)
# dict() 函数用于创建一个字典。
print(dict()) # 创建空字典
print(dict(a='a',b='b',c='c')) # 传入关键字
print(dict(zip(['one', 'two', 'three'], [1, 2, 3]))) # 映射函数方式来构造字典
print(dict([('one', 1), ('two', 2), ('three', 3)])) # 可迭代对象方式来构造字典
# dir([object])
print(dir()) # 获得当前模块的属性列表
print(dir([])) # 查看列表的方法
# divmod(a, b)
print(divmod(7,2))
print(divmod(8,2))
# enumerate() 函数用于将一个可遍历的数据对象组合为一个索引序列,同时列出数据和数据下标,一般用在 for 循环当中。
seasons = ['Spring', 'Summer', 'Fall', 'Winter']
print(list(enumerate(seasons)))
print(list(enumerate(seasons, start=1))) # 小标从 1 开始
# for 循环使用 enumerate
seq = ['one', 'two', 'three']
for i, element in enumerate(seq):
print(i, seq[i])
# eval() 函数用来执行一个字符串表达式,并返回表达式的值。
x=7
print(eval('3*x'))
print(eval('pow(2,2)'))
print('2+2')
n=81
print(eval('n+4'))
# exec 执行储存在字符串或文件中的 Python 语句,相比于 eval,exec可以执行更复杂的 Python 代码。
# 实例 1
exec('print("Hello wolrd")')
exec("""for i in range(5):
print("iter time:%d" % i)
""")
# 实例 2
x = 10
expr = """
z = 30
sum = x + y + z
print(sum)
"""
def func():
y = 20
exec(expr)
exec(expr, {'x': 1, 'y': 2})
exec(expr, {'x': 1, 'y': 2}, {'y': 3, 'z': 4})
func()
# filter() 函数用于过滤序列,过滤掉不符合条件的元素,返回一个迭代器对象,如果要转换为列表,可以使用 list() 来转换。
def is_odd(n):
return n % 2==1
tmplist=filter(is_odd,[1,2,3,4,5,6,7,8,9,10])
newlist=list(tmplist)
print(newlist)
# float() 函数用于将整数和字符串转换成浮点数。
print(float(1))
print(float(112))
print(float(-123.6))
print(float('123'))
# Python2.6 开始,新增了一种格式化字符串的函数 str.format(),它增强了字符串格式化的功能。
print("{} {}".format("hello", "world")) # 不设置指定位置,按默认顺序
print("{0} {1}".format("hello", "world")) # 设置指定位置
print("{1} {0} {1}".format("hello", "world")) # 设置指定位置
# frozenset() 返回一个冻结的集合,冻结后集合不能再添加或删除任何元素。
a = frozenset(range(10)) # 生成一个新的不可变集合
print(a)
b = frozenset('Hello World')
print(b)
# getattr() 函数用于返回一个对象属性值。
class A(object):
bar=1
a=A()
print(getattr(a,'bar')) # 获取属性 bar 值
print(getattr(a,'bar2')) # 属性 bar2 不存在,触发异常
print(getattr(a,'bar2',3)) # 属性 bar2 不存在,但设置了默认值
# globals() 函数会以字典类型返回当前位置的全部全局变量。
print(globals())
a="Hello World" # globals() 函数会以字典类型返回当前位置的全部全局变量。
print(globals())
# hasattr() 函数用于判断对象是否包含对应的属性。
class Coordinate:
x = 10
y = -5
z = 0
point1 = Coordinate()
print(hasattr(point1, 'x'))
print(hasattr(point1, 'y'))
print(hasattr(point1, 'z'))
print(hasattr(point1, 'no')) # 没有该属性
# hash() 用于获取取一个对象(字符串或者数值等)的哈希值。
print(hash('test')) # 字符串
print(hash(1)) # 数字
print(hash(str([1,2,3]))) # 集合
print(hash('test')) # 字典
# help() 函数用于查看函数或模块用途的详细说明。
help('sys') # 查看 sys 模块的帮助
help('str') # 查看 str 数据类型的帮助
help(([1,2,3])) # 查看列表 list 帮助信息
help("a.append") # 显示list的append方法的帮助
# hex() 函数用于将一个指定数字转换为 16 进制数。
print(hex(255))
print(hex(-42))
print(hex(12))
print(type(type(12)))
# id() 函数用于获取对象的内存地址。
print(id("Hello World"))
print(id("1"))
print(id(1))
# isinstance() 函数来判断一个对象是否是一个已知的类型,类似 type()。
print(isinstance(2,int))
print(isinstance(2,str))
print(isinstance(2,(str,int,list))) # 是元组中的一个返回 True
# type() 与 isinstance()区别:
class A:
pass
class B(A):
pass
print(isinstance(A(), A) ) # returns True
type(A()) == A # returns True
isinstance(B(), A) # returns True
type(B()) == A # returns False
# issubclass() 方法用于判断参数 class 是否是类型参数 classinfo 的子类。
class A:
pass
class B(A):
pass
print(issubclass(B,A)) # 返回 True
# iter() 函数用来生成迭代器。
lst=[1,2,3]
for i in iter(lst):
print(i)
# Python len() 方法返回对象(字符、列表、元组等)长度或项目个数。
print(len("Hello World"))
print(len([1,2,3,4,5]))
# list() 方法用于将元组或字符串转换为列表。
# 注:元组与列表是非常类似的,区别在于元组的元素值不能修改,元组是放在括号中,列表是放于方括号中。
aTuple = (123, 'Google', 'Runoob', 'Taobao')
list1 = list(aTuple)
print ("列表元素 : ", list1)
str="Hello World"
list2=list(str)
print ("列表元素 : ", list2)
# locals() 函数会以字典类型返回当前位置的全部局部变量。
def fun(arg): # 两个局部变量:arg、z
z=1
print(locals())
fun(4) # 返回一个名字/值对的字典
# map() 会根据提供的函数对指定序列做映射。
def square(x) : # 计算平方数
return x ** 2
print(map(square, [1,2,3,4,5])) # 计算列表各个元素的平方
print(map(lambda x: x ** 2, [1, 2, 3, 4, 5])) # 使用 lambda 匿名函数
# 提供了两个列表,对相同位置的列表数据进行相加
print(map(lambda x, y: x + y, [1, 3, 5, 7, 9], [2, 4, 6, 8, 10]))
# memoryview() 函数返回给定参数的内存查看对象(Momory view)。
# 所谓内存查看对象,是指对支持缓冲区协议的数据进行包装,在不需要复制对象基础上允许Python代码访问。
v = memoryview(bytearray("abcefg", 'utf-8'))
print(v[1]) # 98
print(v[-1]) #103
print(v[1:4]) #<memory at 0x006DF030>
print(v[1:4].tobytes()) #b'bce'
# next() 返回迭代器的下一个项目。
# 首先获得Iterator对象:
it = iter([1, 2, 3, 4, 5])
# 循环:
while True:
try:
# 获得下一个值:
x = next(it)
print(x)
except StopIteration:
# 遇到StopIteration就退出循环
break
# oct() 函数将一个整数转换成8进制字符串。
print(oct(10))
print(oct(20))
print(oct(15))
# open() 函数常用形式是接收两个参数:文件名(file)和模式(mode)。
# 使用 open() 方法一定要保证关闭文件对象,即调用 close() 方法。
f = open('test.txt')
f.read()
# print() 方法用于打印输出,最常见的一个函数。
print(1)
print("Hello World")
a = 1
b = 'Hello World'
print(a,b)
print("aaa""bbb")
print("aaa","bbb")
print("www","hello world","com",sep=".") # 设置间隔符
# property() 函数的作用是在新式类中返回属性值。
# 语法:class property([fget[, fset[, fdel[, doc]]]])
# Python3 range() 函数返回的是一个可迭代对象(类型是对象),而不是列表类型, 所以打印的时候不会打印列表。
print(list(range(0, 30, 5)))
print(list(range(0, 10, 2)))
print(list(range(0, -10, -1)))
print(list(range(1, 0)))
# repr() 函数将对象转化为供解释器读取的形式。
print(repr('HELLO WORLD'))
print(repr({'hello world': 'hello.com', 'google': 'google.com'}))
# reversed 函数返回一个反转的迭代器。
# 字符串
print(list(reversed('Hello')))
# 元组
print(list(reversed(('H', 'e', 'l', 'l', 'o'))))
# range
print(list(reversed(range(5, 9))))
# 列表
print(list(reversed([1, 2, 4, 3, 5])))
# set() 函数创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算交集、差集、并集等。
x = set('runoob')
y = set('google')
print(x, y)
(set(['b', 'r', 'u', 'o', 'n']), set(['e', 'o', 'g', 'l'])) # 重复的被删除
print(x & y) # 交集
set(['o'])
print(x | y) # 并集
set(['b', 'e', 'g', 'l', 'o', 'n', 'r', 'u'])
print(x - y) # 差集
set(['r', 'b', 'u', 'n'])
# setattr() 函数对应函数 getattr(),用于设置属性值,该属性不一定是存在的。
class A(object):
bar = 1
a = A()
print(getattr(a, 'bar')) # 获取属性 bar 值
setattr(a, 'bar', 5) # 设置属性 bar 值
print(a.bar)
# slice() 函数实现切片对象,主要用在切片操作函数里的参数传递。
myslice = slice(5) # 设置截取5个元素的切片
print(myslice) # slice(None, 5, None)
arr = range(10) # range(0, 10)
print(arr)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(arr[myslice]) # range(0, 5) # 截取 5 个元素
# sorted() 函数对所有可迭代的对象进行排序操作。
# sort 是应用在 list 上的方法,sorted 可以对所有可迭代的对象进行排序操作。
example_list = [5, 0, 6, 1, 2, 7, 3, 4]
print(sorted(example_list, reverse=True))
# python staticmethod 返回函数的静态方法,该方法不强制要求传递参数
class C(object):
@staticmethod
def f():
print('Hello World');
C.f(); # 静态方法无需实例化
cobj = C()
cobj.f() # 也可以实例化后调用
# str() 函数将对象转化为适于人阅读的形式。
s = 'RUNOOB'
print(str(s))
dict = {'runoob': 'runoob.com', 'google': 'google.com'};
print(str(dict))
# sum() 方法对系列进行求和计算。
print(sum([0,1,2]))
print(sum((2, 3, 4), 1)) # 元组计算总和后再加 1
print(sum([0,1,2,3,4], 2)) # 列表计算总和后再加 2
# super() 函数是用于调用父类(超类)的一个方法。
class FooParent(object):
def __init__(self):
self.parent = 'I\'m the parent.'
print ('Parent')
def bar(self,message):
print ("%s from Parent" % message)
class FooChild(FooParent):
def __init__(self):
# super(FooChild,self) 首先找到 FooChild 的父类(就是类 FooParent),然后把类B的对象 FooChild 转换为类 FooParent 的对象
super(FooChild,self).__init__()
print ('Child')
def bar(self,message):
super(FooChild, self).bar(message)
print ('Child bar fuction')
print (self.parent)
if __name__ == '__main__':
fooChild = FooChild()
fooChild.bar('HelloWorld')
# tuple函数将列表转换为元组。
list1= ['Google', 'Taobao', 'Runoob', 'Baidu']
print(tuple(list1))
# type() 函数如果你只有第一个参数则返回对象的类型,三个参数返回新的类型对象。
# type() 与 isinstance()区别:
class A:
pass
class B(A):
pass
isinstance(A(), A) # returns True
type(A()) == A # returns True
isinstance(B(), A) # returns True
type(B()) == A # returns False
# vars() 函数返回对象object的属性和属性值的字典对象。
print(vars())
class Runoob:
a = 1
print(vars(Runoob))
print(vars(Runoob()))
# zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的对象
a = [1,2,3]
b = [4,5,6]
c = [4,5,6,7,8]
zipped = zip(a,b) # 返回一个对象
print(zipped)
print(list(zipped)) # list() 转换为列表
print(list(zip(a,c))) # 元素个数与最短的列表一致
a1, a2 = zip(*zip(a,b)) # 与 zip 相反,zip(*) 可理解为解压,返回二维矩阵式
print(list(a1))
print(list(a2))
# __import__() 函数用于动态加载类和函数 。
# 如果一个模块经常变化就可以使用 __import__() 来动态载入。
# a.py 文件代码:
#!/usr/bin/env python
#encoding: utf-8
import os
print ('在 a.py 文件中 %s' % id(os))
# test.py 文件代码:
#!/usr/bin/env python
#encoding: utf-8
import sys
__import__('a') # 导入 a.py 模块
# 执行 test.py 文件,输出结果为:
# 在 a.py 文件中 4394716136