python3 关键字,内建函数

# Python 关键字
# 关键字	    描述
# False	        布尔值,比较运算的结果。
# True	        布尔值,比较运算的结果。
# None	        表示 null 值。

# and	        逻辑与运算符。
# or	        逻辑或运算符。
# not	        逻辑非运算符。
# in	        检查列表、元组等集合中是否存在某个值。
# is	        测试两个变量是否相等。

# if	        写一个条件语句。
# elif	        在条件语句中使用,等同于 else if。
# else	        用于条件语句。

# for	        创建 for 循环。
# while	        创建 while 循环。
# break	        跳出循环。
# continue	    继续循环的下一个迭代。

# try	        编写 try...except 语句。
# except	    处理异常,发生异常时如何执行。
# finally	    处理异常,无论是否存在异常,都将执行一段代码。
# raise	        产生异常,抛出异常。
# with	        用于简化异常处理。

# as	        创建别名。
# from	        导入模块的特定部分。
# import	    导入模块。

# assert	    用于调试。
# lambda	    创建匿名函数。
# nonlocal	    声明非局部变量。
# global	    声明全局变量。
# class	        定义类。
# def	        定义函数。
# pass	        null 语句,一条什么都不做的语句。

# del	        删除对象。
# return	    退出函数并返回值。
# yield	        结束函数,返回生成器。

# 如果条件返回 False,引发 AssertionError:
# ss = "hello"
# assert ss == "good", "ss not good"  #AssertionError: ss not good




# Python 内置函数	
# 函数	                描述
# help()	            执行内建的帮助系统。
help() #Enter键结束

# 输出python help信息:
"""
Welcome to Python 3.9's help utility!

If this is your first time using Python, you should definitely check out
the tutorial on the Internet at https://docs.python.org/3.9/tutorial/.

Enter the name of any module, keyword, or topic to get help on writing
Python programs and using Python modules.  To quit this help utility and
return to the interpreter, just type "quit".

To get a list of available modules, keywords, symbols, or topics, type
"modules", "keywords", "symbols", or "topics".  Each module also comes
with a one-line summary of what it does; to list the modules whose name
or summary contain a given string such as "spam", type "modules spam".
"""

# print()	            打印标准输出设备。
print("this is print strings.")

# format()	            格式化指定值。
# 参数	描述
# value	任何格式的值。
# format	
# 您要将值格式化为的格式。
# 合法值:
# '<' - 左对齐结果(在可用空间内)
# '>' - 右对齐结果(在可用空间内)
# '^' - 居中对齐结果(在可用空间内)
# '=' - 将符号置于最左侧
# '+' - 使用加号来指示结果是正还是负
# '-' - 负号仅用于负值
# ' ' - 在正数前使用空格
# ',' - 使用逗号作为千位分隔符
# '_' - 使用下划线作为千位分隔符
# 'b' - 二进制格式
# 'c' - 将值转换为相应的 unicode 字符
# 'd' - 十进制格式
# 'e' - 科学格式,使用小写字母 e
# 'E' - 科学格式,使用大写字母 E
# 'f' - 定点编号格式
# 'F' - 定点编号格式,大写
# 'g' - 通用格式
# 'G' - 通用格式(将大写 E 用作科学计数法)
# 'o' - 八进制格式
# 'x' - 十六进制格式,小写
# 'X' - 十六进制格式,大写
# 'n' - 数字格式
# '%' - 百分百格式
x = format(0.8, '%')    #0.8格式化为百分比
print(x)    #80.000000%

del x   # 删除之前定义的x变量
x = format(250, 'x')
print(x) #fa 十六进制

del x   # 删除之前定义的x变量
x = format (10, 'b')
print(x) #1010  二进制


# input()	            允许用户输入。
print("Enter name:")
name = input()
print("Enter age:")
age = input()
print("name:" + name + " age:", age)

# raw_input()   用来获取控制台的输入。
# 语法:raw_input([prompt])
#注意:input() 和 raw_input() 这两个函数均能接收 字符串 ,但 raw_input() 直接读取控制台的输入(任何类型的输入它都可以接收)。
#而对于input() ,它希望能够读取一个合法的 python 表达式,即你输入字符串的时候必须使用引号将它括起来,否则它会引发一个 SyntaxError 。
#python3 里 input() 默认接收到的是 str 类型。
# del x
# x = raw_input("input:")
# print(x)
# print(type(x))

# super()	            返回表示父类的对象。
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    def showinfo(self):
        print("--name:", self.name + " age:", self.age)
    
class Student(Person):
    def __init__(self, name, age):
        super().__init__(name, age)
    def say(self):
        super().showinfo()
        pass

student = Student("XiaoMing", 15)
student.showinfo()  #直接调用父类showinfo()方法,--name: XiaoMing age: 15
student.say()       #子类方法通过super()调用父类showinfo()方法--name: XiaoMing age: 15
print(student.name, student.age)

# abs()	                返回数的绝对值
del x
x = -120
print(abs(x))   #120
x = -120.0
print(abs(x))   #120.0

# max()	                返回可迭代对象中的最大项目。
print(max(2, 18))   #18
print(max(3, 4, 5, 2, 9)) #9
print(max('a', 'z')) #z
print(max("aa", "ab", "ac", "az"))#az

# min()	                返回可迭代对象中的最小项目。
print(min(2, 18))   #2
print(min(3, 4, 5, 2, 9)) #2
print(min('a', 'z')) #a
print(min("aa", "ab", "ac", "az"))#aa

# sum()	                对迭代器的项目进行求和。
list = [10, 20, 30]
print(sum(list))    #60
del list
list = [1.2, 1.3, 1.4, 1.5] 
print(sum(list))    #5.4

# pow() 	            返回 x 的 y 次幂的值。
print(pow(2, 2))    #4
print(pow(10, 3))   #1000

# round()	            对数进行舍入, 小数<0.5丢弃, 小数>0.5进一。
print(round(4.4))       #4
print(round(4.50))      #4
print(round(4.50001))   #5
print(round(4.6))       #5
print(round(4.9))       #5

# range()	            返回数字序列,从 0 开始且以 1 为增量(默认地)。
# 以默认增量1递增
for i in range(0, 10):  # 0 1 2 3 4 5 6 7 8 9
    print(i, end=" ")
print("") # 换行

# 以增量-1递增,即以1递减
for i in range(9, -1, -1): #9 8 7 6 5 4 3 2 1 0
    print(i, end=" ")
print("") # 换行

# 以增量-1递增,即以1递减
for i in range(10, 0, -1): #10 9 8 7 6 5 4 3 2 1
    print(i, end=" ")
print("") # 换行

# 以增量2递增
for i in range(0, 10, 2):#0 2 4 6 8
    print(i, end=" ")
print("") # 换行

for i in range(10, 0, -2):#10,8,6,4,2, 
    print(i, end=",")
print("")

# bin()	                返回数的二进制版本。
print(bin(10))#0b1010
print(bin(128))#0b10000000

# oct()	                把数转换为八进制。
print(oct(7))   #0o7
print(oct(16))  #0o20

# hex()	                把数字转换为十六进制值。
print(hex(9))   #0x9
print(hex(10))  #0xa
print(hex(15))  #0xf
print(hex(65535)) #0xffff

# str()	                返回字符串对象。
del x
x = 1234566788
print(x)        #1234566788
print(type(x))  #<class 'int'>

xx = str(x)
print(xx)       #1234566788
print(type(xx)) #<class 'str'>


# ascii()	            返回对象的可读版本。用转义字符替换 none-ascii 字符。转义非 ASCII 字符:
# 语法 ascii(object)    参数object:	对象,比如字符串、列表、元组、字典等等。
del x,xx
x = "Hello \t world!"
print(x)        #Hello    world!
print(type(x))  #<class 'str'>
xx = ascii(x)
print(xx)       #'Hello \t world!'
print(type(xx)) #<class 'str'>


# bool()	            返回指定对象的布尔值。
# 语法 bool(object)     object	任何对象,比如字符串、列表、数字等等。
del x
x = bool(1) #True
print(x)
x = bool(0) #False
print(x)
x = bool(set()) #False 空集合为False
print(x)
x = bool([]) #False 空列表为False
print(x)
x = bool(()) #False 空元组为False
print(x)
x = bool({
    
    }) #False 空字典为False
print(x)
x = bool("") #False 空字符串为False
print(x)


# int()	                int() 函数把指定值转换为整数。
# 语法 int(value, base) value	可以转换为整数的数字或字符串。base	代表数字格式的数字。默认值:10。
del x
x = int(3.14)
print(x)    #3 默认十进制

x = int("15", 10)
print(x) #15 十进制

x = int("15", 16)
print(x) #21 十六进制

x = int("1010", 2)
print(x) #10 二进制


# float()	            返回浮点数。把指定值转换为浮点数。
# 语法 float(value)     value:能够被转换为浮点数的数字或字符串。
del x
x = float(18)
print(x)        #18.0
print(type(x))  #<class 'float'>

x = float("3.1415926")
print(x)    #3.1415926

# complex()	            返回复数。
# 语法 complex(real, imaginary)
# 参数	    描述
# real	    必需。代表复数实数部分的数字。默认值 0。实数也可以是字符串,比如 '3+5j',在这种情况下,应省略第二个参数。
# imaginary	可选。代表复数的虚数部分。默认值为 0。
del x
x = complex(3, 5)
print(x)                #(3+5j)
print(x.real, x.imag)   #3.0 5.0
print(type(x))          #<class 'complex'>


# chr()	                返回指定 Unicode 代码中的字符。
# 语法 chr(number)      number	代表有效 Unicode 代码点的整数。
# chr() <=> ord()       可以相互转换
del x
x = chr(80)
print(x)        #P
print(type(x))  #<class 'str'>

x = chr(20013)
print(x)        #中

# ord()	                转换表示指定字符的 Unicode 的整数。
# 语法 ord(character)   character	字符串,任何字符。
# ord() <=> chr() 可以相互转换
del x
x = ord('P')
print(x)        #80
print(type(x))  #<class 'int'>

x = ord("中")
print(x)        #20013  "中"的Unicode整数


# bytes()	            返回字节对象。它可以将对象转换为字节对象,或创建指定大小的空字节对象。
# bytes() 和 bytearray() 之间的区别在于,bytes() 返回一个不能修改的对象,而 bytearray() 返回一个可以修改的对象。
# bytes 函数返回一个新的 bytes 对象,该对象是一个 0 <= x < 256 区间内的整数不可变序列。它是 bytearray 的不可变版本。
# 语法 bytes(x, encoding, error)
# _______________________________________________________________________________________________
# │参数	        │描述                                                                            │
# _______________________________________________________________________________________________
# │x	        │创建 bytearray 对象时使用的资源,如果是整数,则会创建指定大小的空 bytearray 对象。  │
# │             │如果是字符串,请确保规定了资源的编码。                                            │
# │encoding	    │字符串的编码                                                                    │
# │error	    │规定若编码失败要做什么。                                                         │
# _______________________________________________________________________________________________
# 参数
# 如果 source 为整数,则返回一个长度为 source 的初始化数组;
# 如果 source 为字符串,则按照指定的 encoding 将字符串转换为字节序列;
# 如果 source 为可迭代类型,则元素必须为[0 ,255] 中的整数;
# 如果 source 为与 buffer 接口一致的对象,则此对象也可以被用于初始化 bytearray。
# 如果没有输入任何参数,默认就是初始化数组为0个元素。
del x
x = bytes(10)
print(x)        #b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00'
print(type(x))  #<class 'bytes'>

x = bytes([1,2,3,4,5])
print(x)        #b'\x01\x02\x03\x04\x05'
print(type(x))  #<class 'bytes'>

x = bytes('hello', 'ascii')
print(x)        #b'hello'
print(type(x))  #<class 'bytes'>

# bytearray()	        返回字节数组。
# bytearray() 方法返回一个新字节数组。这个数组里的元素是可变的,并且每个元素的值范围: 0 <= x < 256。
# 语法 bytearray(x, encoding, error)
# 参数	        描述
# x	            创建 bytearray 对象时使用的资源如果是整数,则会创建指定大小的空 bytearray 对象。
#               如果是字符串,请确保规定了资源的编码。
# encoding	    字符串的编码
# error	        规定若编码失败要做什么。
del x
x = bytearray()
print(x)        #bytearray(b'')
print(type(x))  #<class 'bytearray'>

x = bytearray([1, 2, 3, 4, 5])
print(x)        #bytearray(b'\x01\x02\x03\x04\x05')
print(type(x))  #<class 'bytearray'>

x[0] = 2
print(x)        #bytearray(b'\x02\x02\x03\x04\x05')
print(type(x))  #<class 'bytearray'>

x[3] = ord('a')
print(x)        #bytearray(b'\x02\x02\x03a\x05')

# divmod()	            当参数1除以参数2时,返回商和余数。函数返回当参数 1 除以参数 2 时包含商和余数的元组.
# 语法 divmod(divident, divisor)    divident:数字,被除数。divisor:数字,除数。
del x
x = divmod(9, 2)
print(x)        #(4, 1)
print(type(x))  #<class 'tuple'>


# hash()	            返回指定对象的哈希值。用于获取取一个对象(字符串或者数值等)的哈希值。
# 语法 hash(object)
del x
x = hash("hello")   #字符串
print(x)

x = hash(str([1,5,3,4])) #集合
print(x)



# len()	                返回对象的长度。
# 语法 len(object)      object	必需。对象。必须是序列或集合。
del x
x = len("123456abcdef")
print(x) #12

list = ["one", "two", "three", "four"]
x = len(list)
print(x)    #4


# id()	                返回对象的唯一id。
# id 是对象的内存地址,并且在每次运行程序时都不同。(除了某些具有恒定唯一 id 的对象,比如 -5 到 256 之间的整数)
# 语法 id(object)   object	任何对象,字符串、数字、列表等等。
del x
list = ["one", "two", "three", "four"]
x = id(list)
print(x)    #2556872964288
print(id(x))#2556872868080


# memoryview()	        返回内存视图(memory view)对象。
# 语法 memoryview(obj)  obj	字节对象或字节数组对象。
del x
x = memoryview(b"hello")
print(x)    #<memory at 0x0000029C169E6F40>
print(x[0]) #104    返回首个字符的 Unicode
print(x[1]) #101    返回第二个字符的 Unicode

# type()	            返回对象的类型。
# 语法 type(object, bases, dict)
# 参数	    描述
# object	必需。如果仅设置一个参数,则 type() 函数将返回此对象的类型。
# bases	    可选。规定基类。
# dict	    可选。规定带有类定义的名称空间。
print(type(bool()))     #<class 'bool'>
print(type(int()))      #<class 'int'>
print(type(float()))    #<class 'float'>
print(type(complex()))  #<class 'complex'>
print(type(set()))      #<class 'set'>
print(type(()))         #<class 'tuple'>
print(type({
    
    }))         #<class 'dict'>
print(type(min))        #<class 'builtin_function_or_method'>


# set()	                返回新的集合对象。集合列表中的项目是无序的,因此它将以随机顺序出现
# 语法 set(iterable)    iterable	必需。序列、集合或迭代器对象。
del x
x = set(("aa", "bb", 'cc', 11, 22, 33))
print(x)        #{33, 'bb', 11, 22, 'aa', 'cc'}
print(type(x))  #<class 'set'>
if 11 in x:
    x.remove(11)#remove 11
print(x)        #{33, 'aa', 22, 'bb', 'cc'}

# frozenset()	        返回 frozenset 对象。 frozenset() 函数返回一个不可更改的 Frozenset 对象(类似于 set 对象,仅不可更改)。
# 语法 frozenset(iterable) iterable	可迭代对象,如列表、集合、元组等。
# 尝试更改 Frozenset 项目的值。


# tuple()	            返回元组。不能更改或删除元组中的项目。
# 语法 tuple(iterable)  iterable	必需。序列,集合或可迭代对象。
del x
x = tuple(("one", "two", 'three'))
print(x)        #('one', 'two', 'three')
print(type(x))  #<class 'tuple'>

# list()	            返回列表。  列表对象是有序可更改的集合。
# 语法 list(iterable)   iterable	必需。序列、集合或迭代器对象。
del x
del list
x = list(('apple', 'banana', 'cherry'))
print(x)        #['apple', 'banana', 'cherry']
print(type(x))  #<class 'list'>


# dict()	            返回字典(数组)。字典是无序、可更改和有索引的集合
# 语法 dict(keyword arguments) keyword arguments	必需。任意多的关键字参数,由逗号分隔:key = value、key = value ...
del x
x = dict(name="song", age=11, country="CH")
print(x)        #{'name': 'song', 'age': 11, 'country': 'CH'}
print(type(x))  #<class 'dict'>
print(x.get('name'))#song
x['name']='python'#修改name的值
print(x)    #{'name': 'python', 'age': 11, 'country': 'CH'}

# iter()	            返回迭代器对象。
# 语法 iter(object, sentinel)
# object	必需。可迭代对象。
# sentinel	可选。如果对象是可调用对象,则当返回值与前哨相同时,迭代将停止。

# next()	            返回可迭代对象中的下一项。
# 语法 next(iterable, default)  可以添加默认的返回值,以在迭代结束时返回
# iterable	必需。可迭代对象。
# default	可选。在迭代结束时返回的默认值。

del x
x = iter(["dog", "cat", "hehe"])
print(next(x))  #dog
print(next(x))  #cat
print(next(x))  #hehe


# all()	                如果可迭代对象中的所有项均为 true,则返回 True。
# 如果 iterable 中的所有项目均为 true,则 all() 函数返回 True,否则返回 False。
# 如果该可迭代对象为空,all() 函数也返回 True。
# 在字典上使用时,all() 函数将检查所有键是否为真,而不是值。
# 语法 all(iterable)    iterable	可迭代对象(列表、元组、字典)
del x
l1 = [True, True, 1]
x = all(l1)
print(x)    # True

l2 = [True, True, 0]
x = all(l2)
print(x)    #False

del x
d1 = {
    
    0:"zero", 1:"one"}
x = all(d1)
print(x)    #False

del x
d2 = {
    
    10:"zero", 1:"one"}
x = all(d2)
print(x)    #True

# any()	                如果可迭代对象中的任何项为 true,则返回 True。
# 如果 iterable 中的任何一项为 true,则 any() 函数返回 True,否则返回 False。
# 如果可迭代对象为空,则 any() 函数将返回 False。
# 语法 any(iterable) iterable	可迭代对象(列表、元组、字典)
# 在字典上使用时,any() 函数将检查是否有任何键为真,而不是值。
del x
print(d1)       #{0: 'zero', 1: 'one'}
print(any(d1))  #True
print(d2)       #{10: 'zero', 1: 'one'}
print(any(d2))  #True


# callable()	        如果指定的对象是可调用的,则返回 True,否则返回 False。
# 语法 callable(object)  object	需要测试是否可调用的对象。
x = 100
print(callable(x))      #False

def x():
    print(" x func")
print(callable(x))    #True

# isinstance()	        如果指定的对象是指定对象的实例,则返回 True。
# 如果指定的对象拥有指定的类型,则 isinstance() 函数返回 True,否则返回 False。
# 如果 type 参数是元组,则如果对象是元组中的类型之一,那么此函数将返回 True。
# 语法 isinstance(object, type)
# object	必需。对象。
# type	类型或类,或类型和/或类的元组。
del x
x = isinstance(10, int)
print(x)    #True
x = isinstance(10.0, int)
print(x)    #False


# issubclass()	        如果指定的类是指定对象的子类,则返回 True。
# 语法 issubclass(object, subclass)
# object	必需。对象。
# subclass	class 对象,或 class 对象的元组。
class Age:
    age = 100
class Obj(Age):
    name="python"
    age = Age
del x
x = issubclass(Obj, Age)
print(x)    #True


# property()	        在新式类中返回属性值。获取、设置、删除属性。
# class property([fget[, fset[, fdel[, doc]]]])
# 参数:
# fget -- 获取属性值的函数
# fset -- 设置属性值的函数
# fdel -- 删除属性值函数
# doc -- 属性描述信息
# 返回值:
# 返回新式类属性。
del x
print("--------------------")
class C(object):
    def __init__(self):
        self._x = None
 
    def getx(self):
        return self._x
 
    def setx(self, value):
        self._x = value
 
    def delx(self):
        del self._x
 
    x = property(getx, setx, delx, "I'm the 'x' property.")
    pass

# 如果c是C的实例化, c.x 将触发 getter, c.x = value 将触发 setter, del c.x 触发deleter。
# 如果给定 doc 参数,其将成为这个属性值的 docstring,否则 property 函数就会复制 fget 函数的 docstring(如果有的话)。
c = C
print(type(c.x))    #<class 'property'>
c.x = 1024
print(c.x)          #1024
c.x = "hello"
print(c.x)          #hello
del c.x

# setattr()	            设置对象的属性(属性/方法)。
# setattr() 函数对应函数 getattr(),用于设置属性值,该属性不一定是存在的。
# 语法:setattr(object, name, value) 
# 参数
# object -- 对象。
# name -- 字符串,对象属性。
# value -- 属性值。

# getattr()	            返回指定属性的值(属性或方法)。
# 语法:getattr(object, name[, default])
# 参数
# object    -- 对象。
# name      -- 字符串,对象属性。
# default   -- 默认返回值,如果不提供该参数,在没有对应属性时,将触发 AttributeError。

# hasattr()	            如果指定的对象拥有指定的属性(属性/方法),则返回 True。
# 语法:hasattr(object, name)
# object    -- 对象。
# name      -- 字符串,属性名。


# delattr()	            从指定的对象中删除指定的属性(属性或方法)。无返回值
# 语法:delattr(object, name)
# object    -- 对象。
# name      -- 必须是对象的属性。

class A(object):
    age = 1
a = A
print(getattr(a, 'age'))    #1 (默认值)
setattr(a,'age', 100)
print(getattr(a, 'age'))    #100
setattr(a, 'age', 107)      
print(a.age)                #107

# 判断指定属性是否存在
print(hasattr(a, 'age'))    #True
print(hasattr(a, 'name'))   #False

# 删除属性
# delattr(a, "name")  #没有的属性将引发错误 AttributeError: name
delattr(a, 'age')
print(hasattr(a, 'age'))    #False


# @classmethod()	        把方法转换为类方法。
# classmethod 修饰符对应的函数不需要实例化,不需要 self 参数,
# 但第一个参数需要是表示自身类的 cls 参数,可以来调用类的属性,类的方法,实例化对象等。
class M(object):
    age = 22
    def func1(self):
        print("method func1")
    @classmethod
    def func2(cls):
        print("method func2")
        print(cls.age)
        cls.func1(cls)  #调用func1
# 不需要self参数可直接调用类的方法
M.func2()   
    # method func2
    # 22
    # method func1
# 方法没有@classmethod()修饰,需要self参数调用
M.func1(33)


# @staticmethod()	    把方法转换为静态方法。
# class C(object):
    # @staticmethod
    # def f(arg1, arg2, ...):
# 以上实例声明了静态方法 f,从而可以实现实例化使用 C().f(),当然也可以不实例化调用该方法 C.f()。
class C(object):
    @staticmethod
    def func():
        print(" static method")
C.func()   #静态方法无需实例化
cobj = C()
cobj.func() #也可以实例化后再调用


# eval()	            评估并执行表达式。eval() 函数用来执行一个字符串表达式,并返回表达式的值。
# 语法 eval(expression[, globals[, locals]])
# expression    -- 表达式。
# globals       -- 变量作用域,全局命名空间,如果被提供,则必须是一个字典对象。
# locals        -- 变量作用域,局部命名空间,如果被提供,可以是任何映射对象。
u = 8
print(eval('2 * u'))    #16   (即:2*8=16)

# exec()	            执行指定的代码(或对象)。
# 语法 exec(object[, globals[, locals]])
# object:  必选参数,表示需要被指定的 Python 代码。它必须是字符串或 code 对象。
#           如果 object 是一个字符串,该字符串会先被解析为一组 Python 语句,
#           然后再执行(除非发生语法错误)。如果 object 是一个 code 对象,那么它只是被简单的执行。
# globals: 可选参数,表示全局命名空间(存放全局变量),如果被提供,则必须是一个字典对象。
# locals:  可选参数,表示当前局部命名空间(存放局部变量),如果被提供,可以是任何映射对象。
#           如果该参数被忽略,那么它将会取与 globals 相同的值。
exec('print("Hello World")')    #Hello World
exec('print(2 * u)')            #16


# compile()	            把指定的源作为对象返回,准备执行。compile() 函数将一个字符串编译为字节代码。
# 语法: 
#   compile(source, filename, mode[, flags[, dont_inherit]])
# 参数:
#   source      -- 字符串或者AST(Abstract Syntax Trees)对象。。
#   filename    -- 代码文件名称,如果不是从文件读取代码则传递一些可辨认的值。
#   mode        -- 指定编译代码的种类。可以指定为 exec, eval, single。
#   flags       -- 变量作用域,局部命名空间,如果被提供,可以是任何映射对象。。
#   flags和dont_inherit是用来控制编译源码时的标志
x = "for i in range(0, 10): print(i,end=' ')"
code = compile(x, 'codex.py', 'exec') #编译为字节代码对象
print(code)         #<code object <module> at 0x00000231E3AC39D0, file "codex.py", line 1>
print(type(code))   #<class 'code'>
exec(code)          #0 1 2 3 4 5 6 7 8 9  执行x字符代码结果
print("")

# globals()	            以字典返回当前全局符号表。
# globals 函数返回一个全局变量的字典,包括所有导入的变量。
print(globals())


# locals()	            返回当前本地符号表的更新字典。
# 返回字典类型的局部变量。
print(locals())


# dir()	                返回指定对象的属性和方法的列表。
# dir() 函数不带参数时,返回当前范围内的变量、方法和定义的类型列表;带参数时,返回参数的属性、方法列表。
# 如果参数包含方法__dir__(),该方法将被调用。如果参数不包含__dir__(),该方法将最大限度地收集参数信息。
# 语法 dir([object])    object -- 对象、变量、类型。

print(dir())
#  获得当前模块的属性和方法列表
# ['A', 'Age', 'C', 'M', 'Obj', 'Person', 'Student', '__builtins__', 
# '__cached__', '__doc__', '__file__', '__loader__', '__name__', 
# '__package__', '__spec__', 'a', 'age', 'c', 'code', 
# 'd1', 'd2', 'i', 'l1', 'l2', 'name', 'student', 'x', 'xx']

print(dir([]))
# 获得列表List的属性和方法列表
# ['__add__', '__class__', '__class_getitem__', '__contains__', 
# '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', 
# '__format__', '__ge__', '__getattribute__', '__getitem__', 
# '__gt__', '__hash__', '__iadd__', '__imul__', '__init__',
#  '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', 
# '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', 
# '__repr__', '__reversed__', '__rmul__', '__setattr__', 
# '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 
# 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 
# 'pop', 'remove', 'reverse', 'sort']



# enumerate()	        获取集合(例如元组)并将其作为枚举对象返回。
# 语法 enumerate(sequence, [start=0])
# sequence  -- 一个序列、迭代器或其他支持迭代对象。
# start     -- 下标起始位置。
week = ['Sunday', 'Monday', 'Tuesday', 'Wendesday']
print(week)         #['Sunday', 'Monday', 'Tuesday', 'Wendesday']
print(type(week))   #<class 'list'>
del x
x = list(enumerate(week))   
print(x)            #[(0, 'Sunday'), (1, 'Monday'), (2, 'Tuesday'), (3, 'Wendesday')]
print(type(x))      #<class 'list'>
x2 = list(enumerate(week, start=1))
print(x2)           #[(1, 'Sunday'), (2, 'Monday'), (3, 'Tuesday'), (4, 'Wendesday')]


# filter()	            使用过滤器函数排除可迭代对象中的项目。
#   函数用于过滤序列,过滤掉不符合条件的元素,返回一个迭代器对象,如果要转换为列表,可以使用 list() 来转换。
#   该接收两个参数,第一个为函数,第二个为序列,序列的每个元素作为参数传递给函数进行判断,
#   然后返回 True 或 False,最后将返回 True 的元素放到新列表中。
# 语法 filter(function, iterable)
# function -- 判断函数。
# iterable -- 可迭代对象。
def isodd(n):
    return n % 2 == 1
l8 = [1,2,3,4,5,6,6,7,8,9]
print(l8)   #[1, 2, 3, 4, 5, 6, 6, 7, 8, 9]
tmp = list(filter(isodd, l8))   
print(tmp)      #[1, 3, 5, 7, 9]
print(type(tmp))



# map()	                返回指定的迭代器,其中指定的函数应用于每个项目。
# map() 会根据提供的函数对指定序列做映射。
# 第一个参数 function 以参数序列中的每一个元素调用 function 函数,返回包含每次 function 函数返回值的新列表。
# 语法 map(function, iterable, ...)
# function -- 函数
# iterable -- 一个或多个序列
def square(x):
    return x ** 2
x = list(map(square, [1,2,3,4,5]))    #计算列表各元素的平方
print(x)    #[1, 4, 9, 16, 25]

y = list(map(lambda x: x**2, [1,2,3,4,5])) # 使用 lambda 匿名函数 计算列表各元素的平方
print(y)    #[1, 4, 9, 16, 25]

z = list(map(lambda x, y: x + y, [1,2,3,4,5], [1,2,3,4,5])) # 使用 lambda 匿名函数 计算两个列表的和
print(z)    #[2, 4, 6, 8, 10]

# object()	            返回新对象。 
# object() 函数返回一个空对象。不能向这个对象添加新的属性或方法。
# 这个对象是所有类的基础,它拥有所有类默认的内置属性和方法。
o = object()
print(type(o))


# open()	            打开文件并返回文件对象。
# open() 函数用于打开一个文件,创建一个 file 对象,相关的方法才可以调用它进行读写。
# 语法 open(name[, mode[, buffering]])
# name : 一个包含了你要访问的文件名称的字符串值。
# mode : mode 决定了打开文件的模式:只读,写入,追加等。所有可取值见如下的完全列表。
#        这个参数是非强制的,默认文件访问模式为只读(r)。
# buffering : 如果 buffering 的值被设为 0,就不会有寄存。如果 buffering 的值取 1,访问文件时会寄存行。
#             如果将 buffering 的值设为大于 1 的整数,表明了这就是的寄存区的缓冲大小。如果取负值,寄存区的缓冲大小则为系统默认。

# 模式	描述
# t	文本模式 (默认)。
# x	写模式,新建一个文件,如果该文件已存在则会报错。
# b	二进制模式。
# +	打开一个文件进行更新(可读可写)。
# U	通用换行模式(不推荐)。
# r	以只读方式打开文件。文件的指针将会放在文件的开头。这是默认模式。
# rb	以二进制格式打开一个文件用于只读。文件指针将会放在文件的开头。这是默认模式。一般用于非文本文件如图片等。
# r+	打开一个文件用于读写。文件指针将会放在文件的开头。
# rb+	以二进制格式打开一个文件用于读写。文件指针将会放在文件的开头。一般用于非文本文件如图片等。
# w	打开一个文件只用于写入。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。
# wb	以二进制格式打开一个文件只用于写入。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。一般用于非文本文件如图片等。
# w+	打开一个文件用于读写。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。
# wb+	以二进制格式打开一个文件用于读写。如果该文件已存在则打开文件,并从开头开始编辑,即原有内容会被删除。如果该文件不存在,创建新文件。一般用于非文本文件如图片等。
# a	打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。
# ab	以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。也就是说,新的内容将会被写入到已有内容之后。如果该文件不存在,创建新文件进行写入。
# a+	打开一个文件用于读写。如果该文件已存在,文件指针将会放在文件的结尾。文件打开时会是追加模式。如果该文件不存在,创建新文件用于读写。
# ab+	以二进制格式打开一个文件用于追加。如果该文件已存在,文件指针将会放在文件的结尾。如果该文件不存在,创建新文件用于读写

# file 对象方法
# file.read([size]):size 未指定则返回整个文件,如果文件大小 >2 倍内存则有问题,f.read()读到文件尾时返回""(空字串)。
# file.readline():返回一行。
# file.readlines([size]) :返回包含size行的列表, size 未指定则返回全部行。
# for line in f: print line :通过迭代器访问。
# f.write("hello\n"):如果要写入字符串以外的数据,先将他转换为字符串。
# f.tell():返回一个整数,表示当前文件指针的位置(就是到文件头的字节数)。
# f.seek(偏移量,[起始位置]):用来移动文件指针。偏移量: 单位为字节,可正可负
#       起始位置: 0 - 文件头, 默认值; 1 - 当前位置; 2 - 文件尾
# f.close() 关闭文件
f = open("1.txt", "w+")
f.write("hello world!") #hello world! 写入到文件
f.flush()
f.close()

f = open("1.txt", "r")
line = f.readline()
print(line)         #hello world!

f.seek(2)
line = f.readline() #偏移为+2
print(line)         #llo world!
f.close()

# repr()	            返回对象的可读版本。将对象转化为供解释器读取的形式。
# 语法 repr(object)     object -- 对象。
s = 'hello world'
x = repr(s)
print(x)  #'hello world'

dict = {
    
    'os':'windows', 'lan':'python'}
x = repr(dict)
print(dict) #{'os': 'windows', 'lan': 'python'}
print(x)    #{'os': 'windows', 'an': 'python'}

# reversed()	        返回反转的迭代器。
# 语法 reversed(sequence)   sequence	必需。可迭代对象。
# 类似list.reverse() 方法(反转列表)
l1 = [1,2,3,4,5,6,7,8,9,]
print(l1)   #[1, 2, 3, 4, 5, 6, 7, 8, 9]
l2 = list(reversed(l1))
print(l2)   #[9, 8, 7, 6, 5, 4, 3, 2, 1]


# sorted()	            返回排序列表。可以指定升序或降序。字符串按字母顺序排序,数字按数字排序。
# 语法 sorted(iterable, key=key, reverse=reverse)
# iterable	必需。要排序的序列,列表、字典、元组等等。
# key	    可选。执行以确定顺序的函数。默认为 None。
# reverse	可选。布尔值。False 将按升序排序,True 将按降序排序。默认为 False。

l3 = [2,3,5,2,7,5,9,6,0,8]
print(l3)   #[2, 3, 5, 2, 7, 5, 9, 6, 0, 8] 排序前
l4 = list(sorted(l3))
print(l4)   #[0, 2, 2, 3, 5, 5, 6, 7, 8, 9] 升序排序后
l5 = list(sorted(l3, reverse=True))
print(l5)   #[9, 8, 7, 6, 5, 5, 3, 2, 2, 0] 降序排序后


# slice()	            返回 slice 对象。
# 创建一个元组和一个 slice 对象。使用 slice 对象仅获取元组的前两项:
# 语法 slice(start, end, step)
# start	可选。整数,指定在哪个位置开始裁切。默认为 0。
# end	可选。整数,指定在哪个位置结束裁切。
# step	可选。整数,指定裁切的步进值。默认为 1。
a = ("a", "b", "c", "d", "e", "f", "g", "h")
x = slice(3, 5)
print(x)    #slice(3, 5, None)
print(a[x]) #('d', 'e')

x = slice(3)
print(x)    #slice(None, 3, None)
print(a[x]) #('a', 'b', 'c')

# 从0 ~ 7 以2递增
x = slice(0, 7, 2)
print(x)    #slice(0, 7, 2)
print(a[x]) #('a', 'c', 'e', 'g')

# vars()	            返回对象的 __dict__ 属性。
# 语法 vars([object])   object -- 对象
# 返回对象object的属性和属性值的字典对象,如果没有参数,就打印当前调用位置的属性和属性值 类似 locals()。

# print(vars())
class N:
    n = 29
print(vars(N))
# {'__module__': '__main__', 'n': 29, '__dict__': <attribute '__dict__' of 'N' objects>, 
# '__weakref__': <attribute '__weakref__' of 'N' objects>, '__doc__': None}


# zip()	                从两个或多个迭代器返回一个迭代器。
# 语法 zip([iterable, ...])     iterabl -- 一个或多个迭代器;
# zip() 函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。
# 如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。
a = ("Bill", "Steve", "Elon")
b = ("Gates", "Jobs", "Musk", "Richard")

x = zip(a, b)
print(tuple(x))     #(('Bill', 'Gates'), ('Steve', 'Jobs'), ('Elon', 'Musk'))

aa = [1,2,3,4]
bb = [5,6,7,8]
cc = [15, 26, 37, 48]
ab = zip(aa, bb)
print(tuple(ab))    #((1, 5), (2, 6), (3, 7), (4, 8))
abc = zip(aa,bb,cc)
print(tuple(abc))   #((1, 5, 15), (2, 6, 26), (3, 7, 37), (4, 8, 48))


猜你喜欢

转载自blog.csdn.net/u013420428/article/details/112374726