Python Bulit-in Function

2018-09-29  本文已影响0人  小嘎aa

(转载:https://www.cnblogs.com/weihengblog/p/9090702.html
(参考:http://www.runoob.com/python/python-built-in-functions.html

1. 内置函数列表

1 2 3 4 5
abs() 绝对值 delattr() 删除属性 hash() 哈希值 memoryview() set() 无序不重复元素集
all() 可迭代对象元素判断 dict() 字典 help() 显示帮助信息 min() 最小项 setattr() 设置属性
any() 可迭代对象元素判断 dir() hex() 十六进制 next() 下一个 slice() 切片
ascii() ascii码 divmod() 除 id() id地址 object() sorted() 排序
bin() 二进制 enumerate() 枚举 input() 输入 oct() 八进制 staticmethod() 静态方法
bool() 布尔值 eval() 执行字符串表达式 int() 整数 open() 打开文件 str() 字符串表达式
breakpoint() 设置断点 exec() 执行字符串表达式或代码对象 isinstance() 实例判断 ord() 返回字符的Unicode码值 sum() 求和
bytearray() 对象的字节数组 filter() 过滤 issubclass() 子类判断 pow() x的y次方 super() 调用父类
bytes() 不可变的字节数组 float() 浮点数 iter() 生成迭代器 print() 输出 tuple() 元组
callable() 是否可调用 format() 格式化 len() 个数或长度 property() 属性 type() 对象类型判断或新的类型对象
chr() 根据Unicode码值返回字符 frozenset() 冻结的集合 list()列表 range() 整数可迭代对象 vars()
classmethod() 类的方法 getattr() 得到对象属性的值 locals() 全部局部变量 repr() 字符串表达式 zip() 压缩或解压缩
compile() 字符串表达式编译为代码 globals() 全部全局变量 map() 映射 reversed() 倒转 __import__() 导入
complex() hasattr() 是否有属性 max() 最大项 round() 四舍五入

2. 内置函数详解

print(ascii("abc\n")) #'abc\n'
print(ascii("你好")) #'\u4f60\u597d'

print(bin(100)) #0b1100100
a = bin(100)
print(type(a)) <class 'str'> 返回值是一个字符串

print(bool("123")) --> True

# 之前:
foo()
import pdb; pdb.set_trace()
bar()
# 现在:
foo()
breakpoint()
bar()
a = bytearray("abc",encoding='utf-8',errors="失败")
print(a,type(a)) # bytearray(b'abc') <class 'bytearray'>
print(a[0]) # 97
print(a[1]) # 98
print(a[2]) # 99
>>> class A:                  # 类
...     def method(self):
...             return 0
>>> callable(A)               # 类返回 True
True
>>> a = A()
>>> callable(a)               # 没有实现 __call__, 返回 False
False

print(chr(98)) # b

class Data_test2(object):
        day=0
        month=0
        year=0
    def __init__(self,year=0,month=0,day=0):
        self.day=day
        self.month=month
        self.year=year

    @classmethod
    def get_date(cls,data_as_string):
        #这里第一个参数是cls, 表示调用当前的类名
        year,month,day=map(int,string_date.split('-'))
        date1=cls(year,month,day)
        #返回的是一个初始化后的类
        return date1

    def out_date(self):
        print "year :"
        print self.year
        print "month :"
        print self.month
        print "day :"
        print self.day

那么如何调用呢?

r=Data_test2.get_date("2016-8-6")
r.out_date()

输出:

year :
2016
month :
8
day :
1

complex(1) --> (1+0j)

complex(1,2) --> (1+2j)
complex("1+2j") --> (1+2j)
complex("1+2j",1) --> TypeError: complex() can't take second arg if first is a string

delattr(x,'name') --> del x.name

dict(a=9) --> {'a': 9}

print(divmod(1,2)) # (0,1)
print(divmod(4,2)) # (2,0)
print(divmod(10,3),type(divmod(10,3))) # (3,1)<class 'tuple'>

for i in enumerate([1,2,3,4],start=0):
print(i)
输出:
(0, 1) (start,iterable)
(1, 2)
(2, 3)
(3, 4)

eval("print('Hello')") ---> console打印: Hello

exec("print('Hello')") ---> console打印: Hello
eval()和exec()区别:
1. 如果是简单的表达是求值,eval()和exec()都可以
2. exec()支持字符串、代码对象、复杂的Python代码
3. eval()仅支持有效的表达式求值并返回计算结果

def is_odd(n):
    return n % 2 == 1
list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))
# 结果: [1, 5, 9, 15]
>>>"{} {}".format("hello", "world")    # 不设置指定位置,按默认顺序
'hello world'
>>> "{0} {1}".format("hello", "world")  # 设置指定位置
'hello world'
>>> "{1} {0} {1}".format("hello", "world")  # 设置指定位置
'world hello world'
也可以设置参数
print("网站名:{name}, 地址 {url}".format(name="菜鸟教程", url="www.runoob.com"))
# 通过字典设置参数
site = {"name": "菜鸟教程", "url": "www.runoob.com"}
print("网站名:{name}, 地址 {url}".format(**site))
# 通过列表索引设置参数
my_list = ['菜鸟教程', 'www.runoob.com']
print("网站名:{0[0]}, 地址 {0[1]}".format(my_list))  # "0" 是必须的
数字格式化
>>> print("{:.2f}".format(3.1415926));
3.14

更多数字格式化表达参考

set(可变集合)与frozenset(不可变集合)的区别:
set 无序排序且不重复,是可变的,有add(),remove()等方法。既然是可变的,所以它不存在哈希值。基本功能包括关系测试和消除重复元素。
frozenset是冻结的集合,它是不可变的,存在哈希值,好处是它可以作为字典的key,也可以作为其它集合的元素。缺点是一旦创建便不能更改,没有add(),remove()方法。

input("input:") ---> console:input:

>>>v = memoryview(bytearray("abcefg", 'utf-8'))
>>> print(v[1])
98
>>> print(v[-1])
103
>>> print(v[1:4])
<memory at 0x10f543a08>
>>> print(v[1:4].tobytes())
b'bce'

pow(100, 2) --> 10000

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

        def gettx(self):
                return self.name

        def setx(self,name):
                self.name=name

        def delx(self):
                del self.name

x = property(gettx, setx, delx, "I'm the 'x' property.")
p = Person(name,age)
#如果 p 是 Person 的实例化, p.x 将触发 getter, p.x = value 将触发 setter , del p.x 触发 deleter
#如果给定 doc 参数,其将成为这个属性值的 docstring,否则 property 函数就会复制 fget 函数的 docstring(如果有的话)。
>>>range(10)        # 从 0 开始到 10
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(1, 11)     # 从 1 开始到 11
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> range(0, 30, 5)  # 步长为 5
[0, 5, 10, 15, 20, 25]
>>> dict = {'runoob': 'runoob.com', 'google': 'google.com'};
>>> repr(dict)
"{'google': 'google.com', 'runoob': 'runoob.com'}"

setattr(x, 'foobar', 123)等同于x.foobar = 123

>>>print(vars())
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, '__package__': None}
>>> class Runoob:
...     a = 1
... 
>>> print(vars(Runoob))
{'a': 1, '__module__': '__main__', '__doc__': None}
>>> runoob = Runoob()
>>> print(vars(runoob))
{}
>>>a = [1,2,3]
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b)     # 打包为元组的列表
[(1, 4), (2, 5), (3, 6)]
>>> zip(a,c)              # 元素个数与最短的列表一致
[(1, 4), (2, 5), (3, 6)]
>>> zip(*zipped)          # 与 zip 相反,*zipped 可理解为解压,返回二维矩阵式
[(1, 2, 3), (4, 5, 6)]
上一篇 下一篇

猜你喜欢

热点阅读