三元表达式,内置函数,面向过程编程,模块

时间:2021-08-12
本文章向大家介绍三元表达式,内置函数,面向过程编程,模块,主要包括三元表达式,内置函数,面向过程编程,模块使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。
今日内容:
    1、三元表达式

    2、内置函数

    3、面向过程编程

    4、模块介绍

    5、模块的使用
        import
        from 。。。 import

    6、区分py文件的两种用途
**三元表达式**

def func(x,y):
    if x > y:
        return x
    else:
        return y

res = func(1,2)

x = 1
y = 2

res = 'ok' if x > y else 'no'  # 条件?值1:值2
print(res)

内置函数

**内置函数**

max,min,sorted  #需要掌握

filter,map,reduce  # 用处不大,此类方法可以通过生成式解决,但面试喜欢问偏门的

filter  #过滤
names = ['egon','liusir_dsb',"housir_dsb"]

1.print([name for name in names if name.endswith('dsb')])

2.res = filter(lambda name:name.endswith('dsb'),names) #得到省内存结果
  print(list(res))   #lambda匿名函数(一次性函数),
基于迭代器上来先调用names的iter方法打他变成迭代器,便利出人名传给lambda
返回结果是True,人名留下来

map (映射 '打标签')
names = ['lxx', 'liusir', "housir"]

1. res = [name+"_sb" for name in names]
  print(res)

2. res = map(lambda x: x + "_sb", names)
print(list(res))

reduce (合并相加)
from functools import reduce

res = reduce(lambda x, y: x + y, [1, 2, 3, 4, 5],100)
res = reduce(lambda x, y: x + y, [1, 2, 3, 4, 5])
res = reduce(lambda x, y: x + y, ["a",'b','c'])
print(res)

===============================**内置函数(了解**)===============================
print(abs(-1)) #绝对值
print(all([1, "aa", True]))  #可迭代对象全真则真
print(any([0,"",True])) #可迭代对象有真则真

print(all(""))  # True  空的可迭代对象
print(any([]))  # False  空的可迭代对象

print(bin(11))   #10->2进制    0b1011
print(oct(11))   #10->8进制    0o13
print(hex(11))   #10->16进制   0xb

print(callable(len))  # True 是否为可调用对象
print(callable(10))   # False 是否为可调用对象

aaaa = 1111111111 
def func():
    x = 111111111
    y = 2222222222222
    print(globals()) #全局
    print(locals())  #局部

func()

print(pow(10,2,3))    # 10 ** 2 % 3

l = [1,2,3,4,5,6,7]
s = slice(0,5,2)
print(l[s])   #[1, 3, 5]

s = slice(0,5,2)
l1 = [11,222,333,444,555,666,777,88,999]
print(l1[s])  #[11, 333, 555]
==================================**内置函数(重点)**===============================
int
float
str
list
tuple
dict
set
bool
bytes

s = frozenset({1,2,3})  # 不可变集合
print(type(s))

s = "print('hello')"
eval(s)    #eval(s)可以将字符串的内容当成代码运行

s = "[1,2,3]"
l = eval(s)  
print(l)  #eval(s)可以将字符串的内容当成代码运行,定义成一个列表出来
print(l[0])  # 1
    
#  a.txt文件内容——>  {"name":"egon","age":18}
with open('a.txt',mode='rt',encoding='utf-8') as f:
    data = f.read()  #读出来是个字符串类型 '{"name":"egon","age":18}'
    dic = eval(data)  #重新转成字典
    print(dic['name'])  #用k取值
eval可以将内存中的某一个数据存到文件中(永久保存)

print("start...")
i = 0
while i < 3:
    print(i)
    i+=1
print('end...')    #base64在线编码

import base64   #导模块base64    
exec(base64.b64decode('cHJpbnQoInN0YXJ0Li4uIikKaSA9IDAKd2hpbGUgaSA8IDM6CiAgICBwcml
udChpKQogICAgaSs9MQpwcmludCgnZW5kLi4uJykK'))     
#用在源代码加密,可以制作病毒(骗过浏览器)

print(chr(65))   # A  参照ASCII表相互转换
print(ord("A"))  # 65  参照ASCII表相互转换

l = [1,2,3]
print(dir(l)) 返回l可以点(l.)出来方法

print(divmod(100000,30))  #(商,余数)

res = reversed([1,'a',3]) #颠倒 
print(list(res))          #[3,'a',1]

l = [1,'a',3]    
# res1 = l[::-1]           #切片
res1 = list(reversed(l))   #颠倒
print(res1)

print(round(3.6))  #四舍五入

x = "hello"
y = [1,2,3]
res = zip(x,y)   # x,y传给zip必须是两个可迭代对象
# print(res)   #<zip object at 0x0000024FC1FE3880>
print(list(res))  #[('h', 1), ('e', 2), ('l', 3)]  zip——>快速配对

import time
time.sleep(3)  #让程序睡三秒 

m=__import__("time")    #通过字符串导模块 【 m=__import__("os")】
m.sleep(3)  
==========================**内置函数(面向对象)重点知识**===============================
object
classmethod
staticmethod
property

hasattr
getattr
setattr
delattr

isinstance
issubclass
**面向过程编程**

    核心是过程二字,过程指的是做事的步骤,即先干啥、再干啥、后干啥
    所以说,基于该思想编写程序就好比设计一条流水线

优点:
    复杂的问题流程化、进而简单化
缺点:
    扩展性差(牵一发而动全身)
"""
**1 什么是模块**
    模块就是一系列功能的集合体,可以理解为"工具包"

    **模块的四种类别:**

        1、一个py文件就可以是一个模块,文件名m1.py,模块名为m1
        2、一个包含有__init__.py文件的文件夹称之为包,也是一种模块
        3、
        4、

    **模块有三种来源:**

        1、自带的
            内置
            标准库

        2、第三方模块:pip3 install requests

        3、自定义模块

**2 为何要用模块**

    拿来主义,提升开发效率
    解决冗余问题,让程序变得更加清晰

**3 如何用模块**

import time
print(time)
建spam.py文件
# 被导入的模块
print('======>')
__all__ = ["money","read1"]

money = 100

def read1():
    print('spam.read1访问全局变量: ',money)

def read2():
    read1()
    print("spam.read2")

def change():
    global money
    money = 0
ipmport模块导入 基本语法 import+模块名(不含py)

执行文件(run1.py)
x = 10
首次导入模块发生了三件事
1、会触发模块对应文件的运行,产生一个模块的名称空间
2、运行模块文件的代码,将运行过程中产生的名字都丢到模块的名称空间
3、将模块名称空间的内存地址绑定当前空间中的名字spam
import spam

后续的导入不会触发文件的运行,直接引用之前的导入成果
import spam

使用
print(spam.money)  #100
print(spam.read1)  #访问到空间内存地址
print(spam.read2)
print(spam.change)

例1
money=200
spam.read1()  # 100 (无论调那个都到定义的位置看)

例2
def read1():
    print('run1.read1')

spam.read2()   #(无论调那个都到定义的位置看)
# 调用的是spam.read2下——>read1 
# spam.read访问全局变量:100
# spam.read2

例3
money = 200
spam.change()

print(money)   # 200 没有加前缀跟当前空间要
print(spam.money)  #0
其他语法(import可以导入多个模块逗号隔开,as起个别名)
import spam, os, time
import spam as sm,os as xxx
print(sm.money)

import 优缺点
优点:访问的时候需要加前缀,指名道姓地问某一个名称空间要名字,
肯定不会与当前名称空间中的名字冲突
import spam
money =  100000
print(spam.money)
print(money)

缺点:每次引用都需要加前缀,增加了代码的复杂度
from导入模块也发生了三件事
1、会触发模块对应文件的运行,产生一个模块的名称空间
2、运行模块文件的代码,将运行过程中产生的名字都丢到模块的名称空间
3、在当前执行文件的名称空间中拿到一个名字,该名字指向指向模块名称空间中对应的名字
x = 10
from spam import money
from spam import read1
from spam import read2
from spam import change

第二次导入直接引用之前的成果
from spam import money

使用
money = 200
print(money)

print(read1)
print(read2)
print(change)

money=200
read1()

money = 200
def read1():
    print('run2.read1',money)

read1()

其他语法
from spam import money, read1, read2, change
from spam import money as m, read1, read2 as r2, change

from spam import *
print(money)
print(read1)
print(read2)
print(change)

from导入优缺点:
优点:无需加前缀,代码简洁
缺点:容易与当前名称空间中的名字冲突

原文地址:https://www.cnblogs.com/echoxkx/p/15134997.html