介绍

这一小节的链接https://docs.python.org/3.6/library/intro.html
简单介绍了python。
1,包含了不需要import的对象——内置的函数和exceptions
2,有些module是C编写的,内置在解释器里,因此在看其函数时会发现空的
3,python中对不同操作系统是不一样的,这点要注意,有些函数在Windows和unix是不一样
4,还有一些必须在安装python时选择特定的安装配置

内置函数

这一小节的链接https://docs.python.org/3.6/library/functions.html
内置函数较多,大多数仅仅简单介绍。
下图为列举了内置函数按首字母排列。

abs(x):参数x为整形或浮点型,返回绝对值;x为复数,返回复数的模。
,
,
,
all(iterable):参数为可迭代的,其所有元素为True返回布尔值True,否则为False。iterable的定义,这种继承了抽象类Iterable,有抽象方法__iter__。下图简单列举了Iterable的子类树状图(后面还有不列举了)。具体参考内置类型和数据类型;当iterable内无元素,返回true。

,
,
,
any(iterable):类比all(),输入有true,返回true;空,返回false。
,
,
,
ascii(object):原文解释,输入object,返回一个包含客打印代表这个objext的字符串,如repr()相似,但对non-ASCII字符会溢出(或者说是转义)。
下面对object分类介绍:

输入 输出
module <module ‘drawtree’ from ‘C:\Users\Administrator\PycharmProjects\untitled1\tool\drawtree.py’>
class <class ‘collections.abc.Iterable’>
def <function gettreedic at 0x00000000025A8BF8>
实例化对象 <main.Lqq object at 0x00000000025C10B8>

大概总结一下:都会返回这个object的类型如module、class、function等;module会返回这个文件的绝对路径,function和实例化的对象(就是class的具体对象还会返回这个对象的数据储存地点)。
最后说一下ascii和repr的不同后面就不提了,代码如下,acii(American Standard Code for Information Interchange)不包含汉字,只能利用转义字符\u来打破限制又称escape。

a = '了圣诞节疯狂'
ascii(a)
"'\\u4e86\\u5723\\u8bde\\u8282\\u75af\\u72c2'"
repr(a)

“‘了圣诞节疯狂’”
,
,
,

repr(object):上面ascii也解释了以下,对于repr,一个类可以用通过重写__repr__()控制这函数的输出。
,
,
,
dir([object1]):当无,返回现在的局部变量名;有参数,返回他的有关特性。
如果参数object1内重写了object__dir__().执行dir,如果没有,则执行object.dir()。
规则如下:
If the object is a module object, the list contains the names of the module’s attributes.
If the object is a type or class object, the list contains the names of its attributes, and recursively of the attributes of its bases.
Otherwise, the list contains the object’s attributes’ names, the names of its class’s attributes, and recursively of the attributes of its class’s base classes.

class Person:def __dir__(self):return (['dfdf'])
person =Person()
print(dir(person))#dfdf

,
,
,
help([object]):和dir一样本是为交互模式设计的。
object是类则会返回紧接着class声明的三引号注释,class的方法,class的__dict__(实例变量)和__weakref__(弱引用)(help不显示内容),class的变量和其他属性。
object是独立的函数,返回def前的注释。等不在赘述。

class Person:a=1def __init__(self, age):self.age = agedef __eq__(self, other):if not isinstance(other, Person):print('第一次')return NotImplementedreturn self.age == other.ageimport weakref
person =Person(1)
a=weakref.ref(person)
print(help(person))
print((person.__weakref__()))
print(vars(person))
print(vars(person)==person.__dict__)
以下是返回,可见vars(ob)==ob.__dict__,help不详细显示dict和weakref的内容
Help on Person in module __main__ object:class Person(builtins.object)|  Methods defined here:|  |  __eq__(self, other)|      Return self==value.|  |  __init__(self, age)|      Initialize self.  See help(type(self)) for accurate signature.|  |  ----------------------------------------------------------------------|  Data descriptors defined here:|  |  __dict__|      dictionary for instance variables (if defined)|  |  __weakref__|      list of weak references to the object (if defined)|  |  ----------------------------------------------------------------------|  Data and other attributes defined here:|  |  __hash__ = None|  a = 1None
<__main__.Person object at 0x0000000002571160>
{'age': 1}
True

,
,
,
vars([object]):返回一个module,class,isntance或者其他有_dict__属性的对象。
如module和instance的__dict__是可更新的,但其他对象可能会限制,如类用types.MappingProxyType来阻止更新。
,
,
,

ord(ch):输入一个代表unicode的str,返回一个int;char与之相反。
,
,
,
char(int):与ord相反。
,
,
,
bin(x):输入为整型,返回他的字符串二进制并用“ob”当前缀如(bin(3)—‘ob11’);输入的不是整型,必须满足x有一个返回整型的__index__()方法。这种函数特别多,因此下面给一个例子以后不再赘述。

class Lqq:def __index__(self):return 1
if __name__ == "__main__":
#这里的__name__,你会发现是有值的,规则如下
#当这个module是被执行的文件时,值为__main__;
#而如果不是(如只是被import的),值为module的名即不带后缀的py文件。
#加了这句话,就可以防止,import时,运行被import的module了。a = Lqq()print(bin(a))

结果为1。
,
,
,
oct(x):前缀‘0o’
,
,
,
hex(x):输入int,返回一个前缀为’ox’的int的16进制的字符串;不是int则同bin。
,
,
,
callable(object):首先说明什么叫做callable,可调用的类都是callable(可调用的,如函数a,如何调用呢,a(参数)就是对函数a调用了);而instance实例化的对象,必须有__callalble__方法;function可以callable的。可以callable返回true。解释一下啥叫callable,

class Lqq:@classmethoddef __next__(cls):return 5def __call__(self, *args, **kwargs):return ('dfdfs')
print(callable(Lqq))
a =Lqq()
print(a())
a = Lqq()#加了小括号,可以执行就是对Lqq进行call。不报错就是callable。

这里call了实例化对象a即a()–>调用了__call__。
,
,
,
@classmethod:把一个方法转成类方法(不用实例化就可以调用的方法)。实际上,这是一个装饰器,下面首先介绍啥是装饰器。1
,
,
,
@staticmethod:转成静态方法。类方法和静态方法和一般方法的区别。2
,
,
,
class property(fget=None, fset=None, fdel=None, doc=None):

    class Parrot:'''这里是可以被help(Parrot)打印出来'''def __init__(self):self._voltage = 100000@propertydef voltage(self):"""Get the current voltage."""return self._voltagea = Parrot()print(a.voltage)

输出的是100000,而不是方法,这个装饰器的作用就是把方法的输出转换成同名的属性,即有一个叫做voltage的属性,值为voltage方法的返回值。
,
,
,
compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1):
Compile source into a code object that can be executed by exec() or 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.

首先介绍参数:
source:可以是普通字符串,字节字符串,ast对象
filename:感觉文档解释不通,在查看内置函数的代码由以上介绍,filename用做运行错误的提示的。当code执行错误的时候,会提示中filename中的字符。
如下:
执行的py文件内容

a = compile(  'print(a = 1)',r'C:\Users\Administrator\PycharmProjects\untitled1\c'r'hromeextensionserve\lqq.py','exec')
print(exec(a))

filename文件内容
123123213213213
执行结果

Traceback (most recent call last):File "C:/Users/Administrator/PycharmProjects/untitled1/chromeextensionserve/栏.py", line 4, in <module>print(exec(a))File "C:\Users\Administrator\PycharmProjects\untitled1\chromeextensionserve\lqq.py", line 1, in <module>'123123213213213'
TypeError: 'a' is an invalid keyword argument for this function

mode:

exec 一系列statements
eval 一个表达式
single 一个交互式statement

可选参数flags和dont_inherit是用来控制编译源码时的标志,可以查看PEP236文档来了解这些参数,以及相关编译的说明。如果两者使用缺省参数(也即两者都是零值),在调用本函数编译时,主要使用代码中指明的编译特征来对待;如果flags参数设置有值,而dont_inherit没有设置(即是零值),那么编译代码时,不仅源码的编译特征起作用,而且flags指明的特征也起作用,相当两者的并集;如果参数dont_inherit设置有值(即是非零值),编译语句时只有参数flags指明的编译特征值起作用,即是不使用源码里指明的特征。
optimize: 用来指明编译器使用优化的等级;缺省值是-1,表示使用命令行参数-O中获取的优化等级为准;如果设置值为0(即是不用优化,__debug__是设置true),是没有优化;如果设置值为1,assert语句被删除,__debug__设置为false;如果设置值为2,除了设置值为1的功能之外,还会把代码里文档说明也删除掉,达到最佳优化结果。
,
,
,
eval(expression, globals=None, locals=None):expression可以是str,也可以是compile(如果mode为exec,eval的返回值为None)的结果,其中globals必须是dictionary而locals映射对象。

a=2
print(a)
bb = []
def lqq():statment = compile('a = 1', '', 'exec')exec(statment,globals())
lqq()
print(a)

结果为1

a=2
print(a)
bb = []
def lqq():statment = compile('a = 1', '', 'exec')exec(statment)
lqq()
print(a)

结果为2.
后面两个参数就是决定code中变量的域到底取啥。如果两个参数都没有如第二个例子,默认为局部变量了。
ast.literal_eval() 对于只有字面值的expression,这个函数更加安全。
,
,
,
exec(object[, globals[, locals]]):object可以是str和code。object中的return和yield,返回值为None。
,
,
,
delattr(object,name):删除object的name量;和setattr相反。name是个str;object对象,下面同此。
,
,
,
getattr(object, name[, default]):相当于object.name,如果没有name属性则看是否default是否有值,有返回default;没有提起attributeError。
,
,
,
setattr(object, name, value):设置对象属性值。
,
,
,
hasattr(object,name):利用上面的无default的函数,如果不报错返回true,报错返回false。
,
,
,
super([type[, object-or-type]]):
,
,
,
globals():返回这个module的全局变量,如果函数存在函数方法内,在返回定义这函数方法的module的全局变量。解析模块中globals的键和值。3
,
,
,
locals():以字典形式返回局部变量,locals在函数而不是类中则返回自由变量。注意这里一般不修改locals,因为改变不一定可以在解释器中体现。
,
,
,
hash(object):输入object,返回int成为哈希值。下面举一些小例子。
1.0 == 1 – 比较的是哈希值hash(x)。
1.0 is 1-- false 比较的是id(x)
a = {1:‘2’,1.0,‘4’} 这样定义不会报错。
你会发现字典a的键值也是通过hash的,如a.keys()会返回[1]。

,
,
,
zip(*iterables):返回一个tuple(包含各个iterable的同位置的元素)的iterator,iterable以最短的为标准。而 itertools.zip_longest()会最长的为标准。
而如a =([1,2],[3,4]) a1,b1 = zip(*a) a1为(1,3)。起到了zip的反作用。**的作用[^3]

,
,
,
id(object):返回一个对象的唯一id。在cpython中是对象在内存的位置。这个在学习变量的作用域时,可以帮助理解。
,
,
,
isinstance(object, classinfo):输入对象和类(或是类的tuple值),判断对象是否是类的实例。
例如ininstance(1,(int,str,‘123’))不会报错返回true。
而isinstance(1,(‘123’,int,str)),会报错。
,
,
,
issubclass(class, classinfo):判断是否是子类,其他同上。
,
,
,
input([prompt]):提示语句,阻塞函数,在交互界面输入值确定后就继续执行。
,
,
,
len(s):s为序列或者集合,返回长度int。
,
,
,

divmod(a, b):返回一个tuple,商和余数
,
,
,
pow(x, y[, z]):幂运算,底数,幂指数;如果有z的值,pow(x,y)%y。
,
,
,
sum(iterable[, start]):求和。
‘’.join(sequence)以‘’连接sequnce的各个元素;
math.fsum()有精确度的对浮点值求和。
itertools.chain()链接一系列的iterable。
,
,
,
enumerate(iterable, start=0):输入iterable和数数的第一个数字,返回一个iterator。例子就很明确。
list(enumerate(seasons, start=1))
输出[(1, ‘Spring’), (2, ‘Summer’), (3, ‘Fall’), (4, ‘Winter’)]
,
,
,

filter(function, iterable):从iterable中获取元素,加入function里,如果是true不过滤,结果是iterator[^2]。

,
,
,
map(function, iterable, …):把一个iterable或多个iterable的元素代入function中,返回function的返回值组成的iterator。多个iterable,以最小的为准。
,
,
,
format(value[, format_spec]):控制格式,这都可以说一章了。
format(10, ‘#o’), format(10, ‘o’)----(‘0o12’, ‘12’)

,
,
,
iter(object[, sentinel]):1,如果没有第二个参数,object可以是支持__iter__()(list,range等)或__getitem__()(dict等)的集合对象(否则提出typeerror),返回iterator;2,有第二个参数,object必须是callable(见callable)的,iterator会不不断callobject,直到返回值和sentinel相同的,如果返回的值为sentinel则提出stopiteration。例子如下。

with open('mydata.txt') as fp:for line in iter(fp.readline, ''):process_line(line)a =iter(range(23))def lqq():return a.__next__()bb = iter(lqq,16)
for i in bb:print(i)

打印了0-15.

,
,

reversed(seq):输入一个支持__reversed__()方法或者支持__len__()和以int 0为开始参数的__getitem__()方法,返回一个顺序相反的iterator。
,
,
,
next(iterator[, default]):调用iterator的__next__函数,消耗完后返回default,否则提起stopiteration。
,
,
,
max(iterable, *[, key, default])
max(arg1, arg2, *args[, key])
max([1,23],[21,4])—23
max(-1,-2,1,key=abs)-- -2
max([],default=1)-- 1
如果有两个一样大的返回首先遇到的如下
max(-1,-2,1,2,key=abs)-- -2
,
,
,
min():同上。
,
,
,
sorted(iterable, *, key=None, reverse=False):下面之间用例子说明;
sorted函数和首字母排序
aaa = ‘’‘吴兵,吕骥等.基于出行
链理论的城际旅客出行特征研究[
交通科技,2014(01):102-105.
啊、
吧’’’
from pypinyin import core#下载的汉字转拼音的库
def paixu1(aaa,s,e):#文献首字母排序
a1 = aaa.splitlines()
print(a1)
aaaa = sorted(a1, key=lambda x: ([i[0] for i in core.lazy_pinyin(x[s-1:e])]))
print(aaaa)
paixu1(aaa,1,2)
#sorted函数key默认值为None,应输入一个函数,此处用lambda构造函数,
#变量X为a1的iter的子项。冒号后的值是我们要比较的值,core.lazy_pinyin(x)
#返回的是x的拼音,即“我-wo(小写)”,利用([x[0] for x in core.lazy_pinyin(x[s-1:e])]
#提取首字母
,
,
,
round(number[, ndigits]):最近用不到,用的时候要小心。
,
,
,
open(file, mode=‘r’, buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
输入文件,返回一个与之联系的文件对象,文件不能打开则提出OSerro。
返回的文件对象是io.BufferedIOBase等等(根据mode而不同)
file可以是路径加文件名,接受绝对路径和相对路径。
也可以是fd文件描述符,如果是fd,除非closefd=false,否则当返回的i/o关闭,fd关闭。
mode:详见下图 。多mode组合写在一起就行了如‘rt’默认值。


Note Python doesn’t depend on the underlying operating system’s notion of text files; all the processing is done by Python itself, and is therefore platform-independent.
buffering:

0 关闭buffering,在binary mode
1 选择行缓冲,在text mode
>1 固定缓冲块的字节大小

buffering默认方式如下:看文档。
encoding:text mode使用,编码方式见codecs。
errors:处理encoding问题的方式,[^6]

strick 有问题就报错valueerro
ignore 有问题就忽略,可能导致数据缺失
replace 有问题的地方,用符号代替如?
surrogateescape 编码错误是时用认定的方式替代,还是不行就报错。
xmlcharrefreplace 只支持写文件,不支持的字符用合适的xmlXML character reference &#nnn;替代
backslashreplace 把malformed数据用 backslashed 替代
namereplace 只支持写文件的时候,把不支持的字符写为\N{…}

例子:

import os
os.chdir(r'C:\Users\Administrator\Desktop')
with open('code.txt','w+',errors='xmlcharrefreplace') as fp:print(fp.write('dsasdf对方水电费��p r i n t ( 1 ) �T鬴&T誰膲孴'))
txt文件
dsasdf对方水电费��p r i n t ( 1 ) �T鬴&T誰膲孴import os
os.chdir(r'C:\Users\Administrator\Desktop')
with open('code.txt','w+',errors='namereplace') as fp:print(fp.write('dsasdf对方水电费��p r i n t ( 1 ) �T鬴&T誰膲孴'))txt文件
dsasdf对方水电费\N{REPLACEMENT CHARACTER}\N{REPLACEMENT CHARACTER}p r i n t ( 1 ) \N{REPLACEMENT CHARACTER}T鬴&T誰膲孴

newline:只用于text mode,值可以为None, ‘’, ‘\n’, ‘\r’, ‘\r\n’。
When reading input from the stream, if newline is None, universal newlines mode is enabled. Lines in the input can end in ‘\n’, ‘\r’, or ‘\r\n’, and these are translated into ‘\n’ before being returned to the caller. If it is ‘’, universal newlines mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.
When writing output to the stream, if newline is None, any ‘\n’ characters written are translated to the system default line separator, os.linesep. If newline is ‘’ or ‘\n’, no translation takes place. If newline is any of the other legal values, any ‘\n’ characters written are translated to the given string.
closefd上文已经解释了。
opener:opener必须是callable的如下,就是套用的格式,opener(path,flags)接受open里的参数后进一步处理返回一个open file description。

import os dir_fd = os.open('somedir', os.O_RDONLY)
def opener(path, flags):return os.open(path, flags, dir_fd=dir_fd)with open('spamspam.txt', 'w', opener=opener) as f:print('This will be written to somedir/spamspam.txt', file=f)os.close(dir_fd)  # don't leak a file descriptor

,
,
,
print(objects, sep=’ ‘, end=’\n’, file=sys.stdout, flush=False)
这里
object是指,可以如print(object1,object2…)这样写。
型如sep=‘’,在文档里叫做key arguement。
sep:以什么分隔默认‘’;end:以什么结尾默认‘\n’这就是每次print换行的原因。
file:必须是一个有write(string)方法的对象。如果缺省或者为none,默认为sys.stdout。表示print到哪里。如
a = open(r’C:\Users\Administrator\Desktop\lqq.txt’,‘a+’)
print(‘lqq’,file=a)
a.close()
,
,
,
import(name, globals=None, locals=None, fromlist=(), level=0):
Note This is an advanced function that is not needed in everyday Python programming, unlike importlib.import_module().有点怕。哈哈
这个函数会被,import语句触发。不建议被替换和使用,建议使用 importlib.import_module()。
name:module 名字
gobals和locals如何在包中解释name。
fromlsit:导入的module中部分的名字。
level:用绝对还是相对的import,0,绝对;正数,相对本module的目录上几层搜索。
import spam.ham 相当于
spam = import(‘spam.ham’, globals(), locals(), [], 0)
,
,
,
class str(object=’’)
class str(object=b’’, encoding=‘utf-8’, errors=‘strict’)
无其他参数的print(),和第一种str()差不多。
,
,
,
class slice(stop)
class slice(start, stop[, step])
建立一个slice,a=slice(2);b=[1,2,3,4];b[a]=[1,2]
,
,
,
class int()
,
,
,
class frozenset([iterable]):不可变set
,
,
,
class set([iterable]):输入空,返回空集合;输入iterable,返回set(元素无重复)
,
,
,
class dict():后面详解
,
,
,

class complex([real[, imag]]):复数
complex(1,2)–(1+2j)
complex(‘1+2j’)–(1+2j)字符串里不可有空给
,
,
,

class bool([x]):这个类是int的子类不可被继承。x会被用标准的判断过程判断真假,如果x是假或者空,则返回false,反之为true。
注意这里想【x】的中括号不是list的意思,是这个x可以不输入;docs里也是这样。
,
,
,

class bytearray([source[,encoding[,errors]]]):
下面是构建bytearray的简单介绍:
bytearray(iterable_of_ints) -> bytearray
bytearray(string, encoding[, errors]) -> bytearray
bytearray(bytes_or_buffer) -> mutable copy of bytes_or_buffer
bytearray(int) -> bytes array of size given by the parameter initialized with null bytes
bytearray() -> empty bytes array
他是可变的,即内部定义了大多数常见的可变序列https://docs.python.org/3.6/library/collections.abc.html
的方法。
,
,
,

class bytes([source[, encoding[, errors]]]):不可变版本的bytearray。
https://docs.python.org/3.6/library/stdtypes.html#binary-sequence-types-bytes-bytearray-memoryview
下文内置数据类型会具体介绍。
,
,
,
class float([x]):
,
,
,
class list([iterable])
,
,
,
memoryview(obj)
,
,
,
class object:所有类的基类,不接受参数。注意,他没有__dict__,所以不能给他分配任意特性。
,
,
,

range(start, stop[, step]):range是一个不可变序列。
,
,
,
tuple([iterable]):不可变序列。
,
,
,
class type(object)
class type(name, bases, dict)
只有一个参数,返回object的类型,基本和object.class__一样。isinstance会把子类也考虑进去。
有三个参数时,返回一个新类型的对象。这是种动态建立类的方法。name(str)成为类的__name
,base(tuple,元素为类)成为__bases__,dict是命名空间包括了类体的定义,而且复制到一个标准的dict上成为__dict__属性。
如X = type(‘X’, (object,), dict(a=1))与下面生成的类相同。
class X:
a = 1
class Lqq:
@classmethod
def pr(cls):
print(123)
a =1
class LQQ:
@classmethod
def pr1(cls):
print(1234)
X = type(‘Lqq’, (Lqq,LQQ), dict(a=1))#注意(Lqq,)有逗号是tuple,没不是。
print(Lqq)
X.pr()
X.pr1()
print(vars(X))#返回__dict__

[^2]iterator和iterable的介绍
https://docs.python.org/3.6/library/collections.abc.html
from collections.abc import Iterable,iterator
iterable 中定义了__iter__()方法,而iterator继承了iterable,且定义了__next__()方法。
在简单地说,有前者的方法,可以用循环语句如for,及iterator和iterable都可以;而后者可以用__next__()。

[^3]*的作用
def lqq(a,b):
print(a)
c = (1,2)
lqq(*c)
结果为1,即星号会把这个序列拆开再传给形参。星号和双星号可以传递实参,也可以标记形参。

在新建一个qqpy文件(要被执行的文件)
import lqq
lqq.qwe()
print(globals())

在这里比较一下两个globals的不同(先除去__builtins__),
globals(lqq)的返回值:
name lqq
module名,这里解释一下,上面的 因为执行的不是这个文件,这个只是import带的,__name__不为‘’main‘’。

doc fdsfdsfdsfdgdf
开头三引号之间的文本,而help会返回类和函数定义开头之后的三引号之间的内容。

package
包名

loader <_frozen_importlib_external.SourceFileLoader object at 0x0000000002284D68>

spec ModuleSpec(name=‘lqq’, loader=<_frozen_importlib_external.SourceFileLoader object at 0x0000000002284D68>, origin=‘C:\Users\Administrator\PycharmProjects\untitled1\chromeextensionserve\lqq.py’)

file C:\Users\Administrator\PycharmProjects\untitled1\chromeextensionserve\lqq.py
文件

cached C:\Users\Administrator\PycharmProjects\untitled1\chromeextensionserve_pycache_\lqq.cpython-36.pyc
保存编译结果的文件夹

globals(qq被执行的文件)
name’: ‘main
doc’: None
package’: None
loader’: <_frozen_importlib_external.SourceFileLoader object at 0x0000000001DD2BA8>, ‘spec’: None
annotations’: {}
builtins’: <module ‘builtins’ (built-in)>
file’: ‘C:/Users/Administrator/PycharmProjects/untitled1/chromeextensionserve/栏.py’, ‘cached’: None, ‘lqq’: <module ‘lqq’ from ‘C:\Users\Administrator\PycharmProjects\untitled1\chromeextensionserve\lqq.py’>

思考

1,编写一个类似property的类,使之成为具备一定功能的装置器。
2,完善globals(),全局变量的各个意义


  1. 装饰器
    def logging(level):
    def wrapper(func):
    def inner_wrapper(*args, **kwargs):
    print("[{level}]: enter function {func}()".format(
    level=level,
    func=func.name))
    return func(*args, **kwargs)
    return inner_wrapper
    return wrapper
    @logging(level=‘INFO’)
    def say(something):
    print (“say {}!”.format(something))
    #使用@语法,等同于say = logging(level=‘INFO’)(say)
    @logging(level=‘DEBUG’)
    def do(something):
    print(“do {}…”.format(something))
    if name == ‘main’:
    say(‘hello’)
    do(“my work”)
    response =’’
    a,
    @logging(level=‘INFO’)
    def do(something)等同于,say (*arg,**karg)= logging(level=‘INFO’)(say) (*arg,karg;即把函数say当做参数传递给logging(level=‘INFO’),在赋值给say,即之后say已经不是你认识的那个say了。注:没有打错就是logging(level=‘INFO’),在装饰函数中他的返回值为wraper,则logging(level=‘INFO’)(say)在执行时为wraper(say),wraper(say)则返回func,加上参数即func(arg,**karg)。
    b,
    其次解释装饰函数,这三层存在的意义;
    第一层,有可能有多个函数被装饰,有可能存在区别这些函数的需求;这是就可以在@logging()的添加参数。
    第二层,接受被装饰函数为参数。
    第三层,被装饰函数的参数取值类型数量都可能不一样,因此利用
    argu和
    karg接受参数,接受规则为。
    def lqq(a,b,c,*d,**e):lqq(1,2,3,4,5,6,7,j = 123,l = 12)
    pass 则首先消耗a,b,c即a=1,b=2,c=3. d=[4,5,6,7…](所有其他非j = 123 形式的),e接受 型如j = 123的所有参数。 ↩︎

  2. 类方法的区别
    class Parrot:
    def init(self):
    self._voltage = 100000
    @staticmethod
    def stavoltage():
    “”“Get the current voltage.”""
    return 2
    @classmethod
    def clsvoltage(cls):
    “”“Get the current voltage.”""
    return 1
    def voltage(self):
    “”“Get the current voltage.”""
    return self._voltage
    pa = Parrot()
    print(Parrot.clsvoltage())
    print(pa.voltage())
    print(pa.stavoltage())
    print(Parrot.stavoltage())
    分别输出1
    100000
    2
    2
    静态方法不论是方法还是实例都可以调用,定义是参数不得是self或者cls;类方法cls类调用。 ↩︎

  3. module中globles()的键和值
    建立一个lqq的py文件
    ‘’‘fdsfdsfdsfdgdf’’’
    def qwe():
    a = globals().keys()
    for i in a:
    print(i,globals()[i])
    a =2
    return a
    lqq1 =‘hhh’
    print(‘插眼1’)
    print(name) ↩︎

python3.6library 学习 1.introduction,2.built-infunction相关推荐

  1. Python3 爬虫学习笔记 C06 【正则表达式】

    Python3 爬虫学习笔记第六章 -- [正则表达式] 文章目录 [6.1]关于正则表达式 [6.2]re.match() 方法 [6.2.1]提取内容 [6.2.2]通用匹配 [6.2.3]贪婪匹 ...

  2. Blender 3.0基础入门学习教程 Introduction to Blender 3.0

    成为Blender通才,通过这个基于项目的循序渐进课程学习所有主题的基础知识. 你会学到什么 教程获取:Blender 3.0基础入门学习教程 Introduction to Blender 3.0- ...

  3. 以下用于数据存储领域的python第三方库是-Python3爬虫学习之MySQL数据库存储爬取的信息详解...

    本文实例讲述了Python3爬虫学习之MySQL数据库存储爬取的信息.分享给大家供大家参考,具体如下: 数据库存储爬取的信息(MySQL) 爬取到的数据为了更好地进行分析利用,而之前将爬取得数据存放在 ...

  4. python3视频教程-Python3深度学习视频学习路线

    (关注'AI新视野'公众号,发送"资料'二字,免费获取50G人工智能视频教程!) 经常有粉丝问我:"什么都不懂,怎么入门深度学习?".确实,对于初学者来说,网上繁多的教程 ...

  5. python的程序异常类型,Python3.4学习笔记之类型判断,异常处理,终止程序操作小结...

    本文实例讲述了Python3.4类型判断,异常处理,终止程序操作.分享给大家供大家参考,具体如下: python3.4学习笔记 类型判断,异常处理,终止程序,实例代码: #idle中按F5可以运行代码 ...

  6. python3.4学习笔记(九) Python GUI桌面应用开发工具选择

    python3.4学习笔记(九) Python GUI桌面应用开发工具选择 Python GUI开发工具选择 - WEB开发者 http://www.admin10000.com/document/9 ...

  7. Python3 爬虫学习笔记 C18【爬虫框架 pyspider — 深入理解】

    Python3 爬虫学习笔记第十八章 -- [爬虫框架 pyspider - 深入理解] 文章目录 [18.1]启动参数 [18.2]运行单个组件 [18.2.1]运行 Scheduler [18.2 ...

  8. Python3 爬虫学习笔记 C17【爬虫框架 pyspider — 基本使用】

    Python3 爬虫学习笔记第十七章 -- [爬虫框架 pyspider - 基本使用] 文章目录 [17.1]初识 pyspider [17.2]使用 pyspider [17.2.1]主界面 [1 ...

  9. Python3 爬虫学习笔记 C16【数据储存系列 — Redis】

    Python3 爬虫学习笔记第十六章 -- [数据储存系列 - Redis] 文章目录 [16.1]关于 Redis [16.2]使用 Redis [16.3]Key(键)操作 [16.4]Strin ...

最新文章

  1. C++拾遗(五)语句相关
  2. 如何使用R语言在SAP Analytics Cloud里绘制各种统计图表
  3. android n模拟器,BlueStacks推出Android N模拟器
  4. Android CardView的基本使用
  5. VS2010团队开发调试器无法继续运行该进程,项目文件“”已被重命名或已不再解决方案中
  6. hdu5481 Desiderium
  7. Navicat for oracle 提示 cannot load oci dll,193的解决方法
  8. Q102:光线追踪场景(1)——地球仪
  9. 天池比赛TASK3打卡
  10. 中小企业网站十大通病,你的站有没有?
  11. Shell脚本之H3C网络设备批量巡检
  12. Facebook推广引流工具,Facebook潜客挖掘推广系统
  13. 直流无刷电机FOC控制算法 理论到实践 —— 理论(二)
  14. 微型计算机安装顺序调整记录表,北京理工大学实验一实验报告表.docx
  15. HyperLPR3车牌识别-五分钟搞定: 中文车牌识别光速部署与使用
  16. 开发需要了解的服务器配置
  17. web开发技术情况_如何在不失去思想的情况下成为Web开发人员
  18. 项目打包公共模块失败【error:repackage failed: Unable to find main class】
  19. 跨域通信postMessage
  20. 互联时代,直播,短视频成为知识付费成长的良好土壤

热门文章

  1. 有助于理解分辨率、帧率、压缩率、码率和视频大小的关系式
  2. 语音压缩:压缩率和比特率
  3. linux 密码修改下次,Linux 强制使用者下次登入修改密码
  4. 使用VS2019配置EDK2安装教程
  5. 启动TC的TAO窗口
  6. 2018深信服笔试-抓兔子 DP
  7. 配置jdbc遇到的问题
  8. Windows平台下 C++注册表项重命名实现
  9. MySQL插入emoji表情错误的2种解决方案,Incorrect string value: '\xF0\x9F\x98\x84'
  10. 计算复杂性第八章——空间复杂性