Python菜鸟之路:Python基础-内置函数补充
常用内置函数及用法:
1. callable()
- def callable(i_e_, some_kind_of_function): # real signature unknown; restored from __doc__
- """检查对象object是否可调用。如果返回True,object仍然可能调用失败;但如果返回False,调用对象ojbect绝对不会成功
- Return whether the object is callable (i.e., some kind of function).
- Note that classes are callable, as are instances of classes with a
- __call__() method.
- """
- pass
案例:
- print(callable(0))
- out: False
- print(callable("mystring"))
- out: False
- def add(a, b):
- return a + b
- print(callable(add))
- out: True
- class A:
- def method(self):
- return 0
- print(callable(A))
- out: True
- a = A()
- print(callable(a))
- out: False
- class B:
- def __call__(self):
- return 0
- print(callable(B))
- out: True
- b = B()
- print(callable(b))
- out: True
2. chr() 返回十进制整数对应的ASCII字符。与ord()作用相反
ord() ASCII字符转换为对应十进制。与chr()作用相反
- def chr(*args, **kwargs): # real signature unknown
- """ Return a Unicode string of one character with ordinal i; 0 <= i <= 0x10ffff. """ 取值范围[0, 255]之间的正数
- pass
- def ord(*args, **kwargs): # real signature unknown
- """ Return the Unicode code point for a one-character string. """
- pass
案例:
- print(chr(97))
- out: a
- print(ord('a'))
- out: 97
3. eval 把字符串当做表达式,执行。有返回值,返回值就是表达式执行的结果
exec 比eval更牛逼的功能。但是无返回值。只是去执行python代码或者字符串、表达式.如果接收字符串,则编译成python代码并执行。如果接收代码,则执行。
- def eval(*args, **kwargs): # real signature unknown
- """
- Evaluate the given source in the context of globals and locals.
- The source may be a string representing a Python expression
- or a code object as returned by compile().
- The globals must be a dictionary and locals can be any mapping,
- defaulting to the current globals and locals.
- If only globals is given, locals defaults to it.
- """
- pass
- def exec(*args, **kwargs): # real signature unknown
- """
- Execute the given source in the context of globals and locals.
- The source may be a string representing one or more Python statements
- or a code object as returned by compile().
- The globals must be a dictionary and locals can be any mapping,
- defaulting to the current globals and locals.
- If only globals is given, locals defaults to it.
- """
- pass
案例:
- s = "print(123)"
- r = compile(s, "<string>", "exec")
- exec(r)
- out:123
- s = 'print(123)'
- ret = exec(s)
- out: 123
- print(ret)
- out: None
- s = "8*8"
- ret = eval(s)
- print(ret)
- out: 64
4. compile(source, filename, mode[, flags[, dont_inherit]])
将source编译为代码或者AST对象。代码对象能够通过exec语句来执行或者eval()进行求值。
- def compile(*args, **kwargs): # real signature unknown
- """
- Compile source into a code object that can be executed by exec() or eval(). 将source编译为代码或者AST对象。代码对象能够通过exec语句来执行或者eval()进行求值。
- The source code may represent a Python module, statement or expression.
- The filename will be used for run-time error messages.
- The mode must be 'exec' to compile a module, 'single' to compile a
- single (interactive) statement, or 'eval' to compile an expression.
- The flags argument, if present, controls which future statements influence
- the compilation of the code.
- The dont_inherit argument, if true, stops the compilation inheriting
- the effects of any future statements in effect in the code calling
- compile; if absent or false these statements do influence the compilation,
- in addition to any features explicitly specified.
- """
- pass
案例:
- s = "print(123)"
- r = compile(s, "<string>", "exec")
- # 如果不传 <string>参数,就需要传递一个"文件名"参数
- exec(r)
扩充知识:statement和expression
expression是表达式,就是加减乘除等各种运算符号联接起来的式子,statement是语句,如if语句,while,复制语句等。statement里含有expression.
5. random 生成随机数模块,是一个隐藏的random.Random类的实例的random方法。
案例1:生成随机字符串+数字
- import random
- li = []
- for i in range(6):
- r = random.randrange(0,5)
- if r == 2 or r == 4:
- num = random.randrange(0,10)
- li.append(str(num))
- else:
- c = random.randrange(65, 91)
- li.append(chr(c))
- print("".join(li))
案例2:生成随机验证码
- import random
- def generate_verification_code(len=6):
- ''' 随机生成6位的验证码 '''
- # 注意: 可以生成0-9A-Za-z的列表,也可以指定个list,这里很灵活
- # 比如: code_list = ['$','*','.','!','@','~','^','*','<'] # list中可以加特殊字符来增加复杂度
- code_list = ['$','*','.','!','@','~','^','*','<']
- for i in range(10): # 0-9数字
- code_list.append(str(i))
- for i in range(65, 91): # 对应从“A”到“Z”的ASCII码
- code_list.append(chr(i))
- for i in range(97, 123): #对应从“a”到“z”的ASCII码
- code_list.append(chr(i))
- myslice = random.sample(code_list, len) # 从list中随机获取6个元素,作为一个片断返回
- verification_code = ''.join(myslice) # list to string
- return verification_code
- code = generate_verification_code(12)
- print(code)
- out: nf1JKl7j<E^t
6. dir() 快速获取模块或者函数提供的功能。返回一个功能列表
help() 查看对象的功能,可以快速打印源码
- def dir(p_object=None): # real signature unknown; restored from __doc__
- """
- dir([object]) -> list of strings
- If called without an argument, return the names in the current scope.
- Else, return an alphabetized list of names comprising (some of) the attributes
- of the given object, and of attributes reachable from it.
- If the object supplies a method named __dir__, it will be used; otherwise
- the default dir() logic is used and returns:
- for a module object: the module's attributes.
- for a class object: its attributes, and recursively the attributes
- of its bases.
- for any other object: its attributes, its class's attributes, and
- recursively the attributes of its class's base classes.
- """
- return []
dir.source
案例:
- print(dir(dict))
- out: ['__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__init__', '__iter__', '__le__', '__len__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'clear', 'copy', 'fromkeys', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
- print(help(dict))
- out: Help on class dict in module builtins:
- class dict(object)
- | dict() -> new empty dictionary
- | dict(mapping) -> new dictionary initialized from a mapping object's
- | (key, value) pairs
- | dict(iterable) -> new dictionary initialized as if via:
- | d = {}
- | for k, v in iterable:
- | d[k] = v
- | dict(**kwargs) -> new dictionary initialized with the name=value pairs
- | in the keyword argument list. For example: dict(one=1, two=2)
- |
- | Methods defined here:
- |
- | __contains__(self, key, /)
- | True if D has a key k, else False.
- |
- | __delitem__(self, key, /)
- | Delete self[key].
- |
- | __eq__(self, value, /)
- | Return self==value.
- |
- | __ge__(self, value, /)
- | Return self>=value.
- |
- | __getattribute__(self, name, /)
- | Return getattr(self, name).
- |
- | __getitem__(...)
- | x.__getitem__(y) <==> x[y]
- |
- | __gt__(self, value, /)
- | Return self>value.
- |
- | __init__(self, /, *args, **kwargs)
- | Initialize self. See help(type(self)) for accurate signature.
- |
- | __iter__(self, /)
- | Implement iter(self).
- |
- | __le__(self, value, /)
- | Return self<=value.
- |
- | __len__(self, /)
- | Return len(self).
- |
- | __lt__(self, value, /)
- | Return self<value.
- |
- | __ne__(self, value, /)
- | Return self!=value.
- |
- | __new__(*args, **kwargs) from builtins.type
- | Create and return a new object. See help(type) for accurate signature.
- |
- | __repr__(self, /)
- | Return repr(self).
- |
- | __setitem__(self, key, value, /)
- | Set self[key] to value.
- |
- | __sizeof__(...)
- | D.__sizeof__() -> size of D in memory, in bytes
- |
- | clear(...)
- | D.clear() -> None. Remove all items from D.
- |
- | copy(...)
- | D.copy() -> a shallow copy of D
- |
- | fromkeys(iterable, value=None, /) from builtins.type
- | Returns a new dict with keys from iterable and values equal to value.
- |
- | get(...)
- | D.get(k[,d]) -> D[k] if k in D, else d. d defaults to None.
- |
- | items(...)
- | D.items() -> a set-like object providing a view on D's items
- |
- | keys(...)
- | D.keys() -> a set-like object providing a view on D's keys
- |
- | pop(...)
- | D.pop(k[,d]) -> v, remove specified key and return the corresponding value.
- | If key is not found, d is returned if given, otherwise KeyError is raised
- |
- | popitem(...)
- | D.popitem() -> (k, v), remove and return some (key, value) pair as a
- | 2-tuple; but raise KeyError if D is empty.
- |
- | setdefault(...)
- | D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
- |
- | update(...)
- | D.update([E, ]**F) -> None. Update D from dict/iterable E and F.
- | If E is present and has a .keys() method, then does: for k in E: D[k] = E[k]
- | If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v
- | In either case, this is followed by: for k in F: D[k] = F[k]
- |
- | values(...)
- | D.values() -> an object providing a view on D's values
- |
- | ----------------------------------------------------------------------
- | Data and other attributes defined here:
- |
- | __hash__ = None
- None
help.test
7. divmod(x, y) 得到x/y的商和余数 (商, 余数)
- print(divmod(5,4))
- out: (1, 1)
8. isinstance() 判断对象是谁的实例, 可以向上查找,甚至查找父类的父类。返回True or False
- print(isinstance('a', str))
- out: True
9. globals() 代表所有的全局变量,返回的 dictionary 的任何的改动都会直接影响到全局变量。
locals() 代表所有的局部变量,返回 dictionary 的函数, 并且在 dictionary 中设置一个值。是一个只读dict
- def foo(arg, a):
- x = 1
- y = 'xxxxxx'
- for i in range(10):
- j = 1
- k = i
- print locals()
- #调用函数的打印结果
- foo(1,2)
- out: {'a': 2, 'i': 9, 'k': 9, 'j': 1, 'arg': 1, 'y': 'xxxxxx', 'x': 1}
10. len 返回对象的长度,python2中按照字节计算 , python3按照字符来计算
- print(len("诸葛亮"))
- #python2
- out: 9
- #python3
- out: 3
11. hash 返回对象的哈希值
- print(hash("abc"))
- out: -8810164989165849038
12. filter 把传入的函数依次作用于每个元素,然后根据返回值是True还是False决定保留还是丢弃该元素。
- class filter(object):
- """
- filter(function or None, iterable) --> filter object
- Return an iterator yielding those items of iterable for which function(item)
- is true. If function is None, return the items that are true.
- """
- def __getattribute__(self, *args, **kwargs): # real signature unknown
- """ Return getattr(self, name). """
- pass
- def __init__(self, function_or_None, iterable): # real signature unknown; restored from __doc__
- pass
- def __iter__(self, *args, **kwargs): # real signature unknown
- """ Implement iter(self). """
- pass
- @staticmethod # known case of __new__
- def __new__(*args, **kwargs): # real signature unknown
- """ Create and return a new object. See help(type) for accurate signature. """
- pass
- def __next__(self, *args, **kwargs): # real signature unknown
- """ Implement next(self). """
- pass
- def __reduce__(self, *args, **kwargs): # real signature unknown
- """ Return state information for pickling. """
- pass
filter.source
案例:
- def is_odd(n):
- return n % 2 == 1
- print(list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15])))
- out: [1, 5, 9, 15]
13. map 将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回
- class map(object):
- """
- map(func, *iterables) --> map object
- Make an iterator that computes the function using arguments from
- each of the iterables. Stops when the shortest iterable is exhausted. 将迭代对象按照func的方法进行运算逐个,最终返回一个list对象
- """
- def __getattribute__(self, *args, **kwargs): # real signature unknown
- """ Return getattr(self, name). """
- pass
- def __init__(self, func, *iterables): # real signature unknown; restored from __doc__
- pass
- def __iter__(self, *args, **kwargs): # real signature unknown
- """ Implement iter(self). """
- pass
- @staticmethod # known case of __new__
- def __new__(*args, **kwargs): # real signature unknown
- """ Create and return a new object. See help(type) for accurate signature. """
- pass
- def __next__(self, *args, **kwargs): # real signature unknown
- """ Implement next(self). """
- pass
- def __reduce__(self, *args, **kwargs): # real signature unknown
- """ Return state information for pickling. """
- pass
map.source
案例:
- def f(x):
- return x * x
- r = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])
- print(list(r))
14. repr 通过repr执行对象的时候,会自动调用类里边__repr__的方法
- print(repr('e'))
- print(type(repr('e')))
- print(help(str.__repr__))
- out:
- 'e'
- Help on wrapper_descriptor:
- __repr__(self, /)
- Return repr(self).
- None
- <class 'str'>
15. reversed 反转,调用对象的__reverse__的方法
- li = [1,2,3,4,5]
- print(list(reversed(li)))
- print(help(list.__reversed__(li)))
- out:
- [5, 4, 3, 2, 1]
- Help on list_reverseiterator object:
- class list_reverseiterator(object)
- | Methods defined here:
- |
- | __getattribute__(self, name, /)
- | Return getattr(self, name).
- |
- | __iter__(self, /)
- | Implement iter(self).
- |
- | __length_hint__(...)
- | Private method returning an estimate of len(list(it)).
- |
- | __next__(self, /)
- | Implement next(self).
- |
- | __reduce__(...)
- | Return state information for pickling.
- |
- | __setstate__(...)
- | Set state information for unpickling.
- None
16. round(x, n) 返回 x 的小数点四舍五入到n个数字,如果数字有一位小数,遵循5舍6入原则。其余情况,遵循四舍五入原则。
- print(round(4.4))
- print(round(4.5))
- print(round(4.6))
- print("round(80.23456, 2) : ", round(80.23456, 2))
- print("round(100.000056, 3) : ", round(100.000056, 3))
- print("round(-100.000056, 5) : ", round(-100.000056, 5))
- out:
- 4
- 4
- 5
- round(80.23456, 2) : 80.23
- round(100.000056, 3) : 100.0
- round(-100.000056, 5) : -100.00006
17. slice 切片操作slice(start, [stop], [step]),不如直接用对象本身支持的切片操作,起码对象自身的切片,使用方式上简单。
- s = [1,2,3,4,5,6,8]
- myslice = slice(2,4)
- print(s[myslice])
18. sorted() 对对象进行排序,返回一个新的对象。与对象本身的sort方法不同,本身的sort直接修改对象本身。
- s = [1,4,2,5,3]
- print("sorted s out: ", sorted(s))
- new_s = sorted(s)
- print("origin s :", s)
- print("new s create:", new_s)
- s.sort(reverse=True)
- print("s is changed:", s)
19. vars() 无参数的情况等同locals()
- class A:
- a = 1
- b = 'xxxxxx'
- def __dict__(self):
- x = 1
- y = 2
- print(vars(A))
9 out: {'__doc__': None, '__module__': '__main__', '__dict__': <function A.__dict__ at 0x0000000000B7F598>, 'a': 1, 'b': 'xxxxxx', '__weakref __': <attribute '__weakref__' of 'A' objects>}
20. zip() 接受任意多个(包括0个和1个)序列作为参数,返回一个tuple列表
- x = [1, 2, 3]
- y = [4, 5, 6]
- z = [7, 8, 9]
- xyz = zip(x, y, z)
- print(list(xyz))
- out:
- [(1, 4, 7), (2, 5, 8), (3, 6, 9)]
- x = [1, 2, 3]
- y = [4, 5, 6, 7]
- print(list(zip(x, y)))
- out:
- [(1, 4), (2, 5), (3, 6)]
21. 反射的几个内置方法:hasattr(),setattr(),getattr(),delattr()
反射的概念:利用字符串的形式去对象(模块)中操作(寻找、检查、删除、设置)成员,就是反射
1)getattr() 获取对象的某个属性或方法,如果default未给出,则语法:getattr(object, name, default=None)
- def getattr(object, name, default=None): # known special case of getattr
- """
- getattr(object, name[, default]) -> value
- Get a named attribute from an object; getattr(x, 'y') is equivalent to x.y.
- When a default argument is given, it is returned when the attribute doesn't
- exist; without it, an exception is raised in that case.
- """
- pass
代码案例:
- a = []
- print(getattr(a, 'append'))
- out: <built-in method append of list object at 0x0000000000703E48>
- print(getattr(a, 'delete','not found'))
- out: not found
- print(getattr(a, 'delete'))
- out: AttributeError: 'list' object has no attribute 'delete'
2)hasattr() 用于确定一个对象是否具有某个属性。语法:hasattr(object, name) -> bool 判断object中是否有name属性,返回一个布尔值。
- def hasattr(*args, **kwargs): # real signature unknown
- """
- Return whether the object has an attribute with the given name.
- This is done by calling getattr(obj, name) and catching AttributeError.
- """
- pass
代码案例:
- a = []
- print(hasattr(a, 'append'))
- print(hasattr(a, 'delete'))
- out:
- True
- False
3)setattr()
- def setattr(x, y, v): # real signature unknown; restored from __doc__
- """
- Sets the named attribute on the given object to the specified value.
- setattr(x, 'y', v) is equivalent to ``x.y = v''
- """
- pass
代码案例:
- class T:
- def __init__(self):
- pass
- a = T()
- setattr(a, "bb", "")
- print(a.bb)
- out: 123
4)delattr()
- def delattr(x, y): # real signature unknown; restored from __doc__
- """
- Deletes the named attribute from the given object.
- delattr(x, 'y') is equivalent to ``del x.y''
- """
- pass
代码案例:
- class T:
- def __init__(self):
- pass
- a = T()
- setattr(a, "bb", "")
- print(a.bb)
- delattr(a, "bb")
- print(hasattr(a, "bb"))
- out:
123
False
22. staticmethod,super 待续
23. property python内置的装饰器,以后补全
未完,待续!
Python菜鸟之路:Python基础-内置函数补充的更多相关文章
- python基础——内置函数
python基础--内置函数 一.内置函数(python3.x) 内置参数详解官方文档: https://docs.python.org/3/library/functions.html?highl ...
- Python之路----内置函数补充与匿名函数
内置函数补充:reversed()保留原列表,返回一个反向的迭代器 l = [1,2,3,4,5] l.reverse() print(l) l = [1,2,3,4,5] l2 = reversed ...
- Python开发基础-Day11内置函数补充、匿名函数、递归函数
内置函数补充 python divmod()函数:把除数和余数运算结果结合起来,返回一个包含商和余数的元组(a // b, a % b) 语法: divmod(a, b) #a.b为数字,a为除数,b ...
- 《Python》 内置函数补充、匿名函数、递归初识
一.内置函数补充: 1.数据结构相关(24): 列表和元祖(2):list.tuple list:将一个可迭代对象转化成列表(如果是字典,默认将key作为列表的元素). tuple:将一个可迭代对象转 ...
- python学习笔记:第14天 内置函数补充和递归
一.匿名函数 匿名函数主要是为了解决一些简单需求而设计的一种函数,匿名函数的语法为: lambda 形参: 返回值 先来看一个例子: # 计算n的n次方 In[2]: lst = lambda n: ...
- python基础之内置函数补充、匿名函数、递归函数
内置函数补充 python divmod()函数:把除数和余数运算结果结合起来,返回一个包含商和余数的元组(a // b, a % b) 语法: 1 divmod(a, b) #a.b为数字,a为除数 ...
- Python中字符串String的基本内置函数与过滤字符模块函数的基本用法
Python中字符串String的基本内置函数与用法 首先我们要明白在python中当字符编码为:UTF-8时,中文在字符串中的占位为3个字节,其余字符为一个字节 下面就直接介绍几种python中字符 ...
- python 之 面向对象(多态性、装饰器方法 内置函数补充)
7.6 多态性 1 什么是多态性 多态指的是同一种事物多种形态,在程序中用继承可以表现出多态.多态性:可以在不用考虑对象具体类型的前提下而直接使用对象下的方法 2.为什要用多态 用基类创建一套统一的规 ...
- 自学Python3.3-函数分类(内置函数补充)
自学Python之路-Python基础+模块+面向对象自学Python之路-Python网络编程自学Python之路-Python并发编程+数据库+前端自学Python之路-django 自学Pyth ...
随机推荐
- Selenium-java-Log4j环境搭建
1.导入Log4j 2.Build Path 3.在/src/main/resource目录下创建文件,命名为 log4j.properties 4.文件的内容是, 直接复制 ### 设置根 定义 ...
- 2017.6.30 IDEA插件--gsonfomat的安装与使用
参考来自:http://www.cnblogs.com/1024zy/p/6370305.html 1.安装 2.使用 (1)新建一个空类 (2)在空类里按快捷键:alt+s,打开gsonformat ...
- 模拟服务器MockServer之Moco详细介绍
转载:http://blog.csdn.net/vite_s/article/details/54583243 前面一篇介绍了如何用mockito来测试我们的一些异步任务,例如网络请求时候的异步回调. ...
- 在vs2010中编译log4cxx-0.10.0具体方法(从下载、编译、解决错误具体介绍)
一. 简单介绍 log4cxx是Java社区著名的log4j的c++移植版.用于为C++程序提供日志功能,以便开发人员对目标程序进行调试和审计,log4cxx是apache软件基金会的开源项目,基于A ...
- UVA 111 (复习dp, 14.07.09)
History Grading Background Many problems in Computer Science involve maximizing some measure accor ...
- iOS实录:GCD使用小结(一)
导语:在iOS中,多线程方案有四种:pthread.NSThread.NSOperation & NSOperationQueue 和 GCD,但是开发中GCD使用得最多,本文主要总结一下我使 ...
- eclipse maven tools.jar找不到y也就是在这个
Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile ...
- 通过mysql show processlist 命令检查mysql锁的方法
作者: 字体:[增加 减小] 类型:转载 时间:2010-03-07 show processlist 命令非常实用,有时候mysql经常跑到50%以上或更多,就需要用这个命令看哪个sql语句占用资源 ...
- JDBC技术总结(三)
1. 数据库连接池 JDBC部分的前两个总结主要总结了一下JDBC的基本操作,而且有个共同点,就是应用程序都是直接获取数据库连接的.这会有个弊端:用户每次请求都需要向数据库获得连接,而数据库创建连接通 ...
- Jenkins与Docker相关的Plugin使用
原文地址:http://blog.csdn.net/ztsinghua/article/details/52128140 Jenkins与Docker相关的Plugin 在Jenkins Plugin ...