python命名元祖写法
# 命名元組
from collections import namedtuple
name_info = namedtuple('info_student',["name","age","gander"])
name = name_info("張三","18","男")
print(name)
print(name.name)
列表推导式写法
for i in range(1,101):
url = "page{}".format(i)
urls.append(url)
print(urls)
urls1 = ['page{}'.format(i) for i in range(1,101)]
print(urls1)
字典推导式
dict1 = {i : i + 1 for i in range(10)}
生成器表达式
tu = (i for i in range(10))
print(tu)
print(next(tu)) # 输出0
print(next(tu)) #输出1
函数式的生成器
def gen_func():
yield 100
print("hello_world")
yield 1000
yield 10000
res = gen_func()
print(res) # 返回一个生成器对象
print(next(res)) 100
print(next(res)) 1000
print(next(res)) 10000
字典推导式快速把字符串变成字典
a = "skkss=11123asss;sadsadsa=11231sadsasa;sadasdasd=ssssada;sadsddsa=sdadassss"
s = {item.split("=")[0]:item.split("=")[1] for item in a.split(";")}
print(s) #{'skkss': '11123asss', 'sadsadsa': '11231sadsasa', 'sadasdasd': 'ssssada', 'sadsddsa': 'sdadassss'}
filter() 和 map()
def fun(n):
return n > 1
res = filter(fun, li)
print(list(res)) # [2, 2, 2, 23123, 123, 12]
res1 = map(fun,li)
print(list(res1)) # [True, True, True, False, False, False, True, True, False, True]
匿名函數
def fuc1(a, b):
return a + b
# 匿名函数适应场景 简单的函数定义 只有一个表达式
res = lambda a, b: a + b
print(res(1,2))
# 匿名函数推荐这种用法 执行完立即是否 节省内存
res = (lambda a, b: a + b)(1, 2)
print(res)
闭包的条件
# 满足闭包的三个条件
# 函数内嵌套一个函数
# 外层函数返回了内存函数
# 函数内引用一个非全局变量
def func():
num = 100
def cook_sum():
print("计算")
print(num)
return cook_sum
res = func()
装饰器用法
def login(func):
def fun():
username = "python"
password = "python"
uer = input("请输入账号")
pwd = input("请输入密码")
if uer == username and pwd == password:
func()
else:
print("用户名或者密码错误")
return fun
@login # 登录成功后才能访问首页 => index = login(index)
def index():
print("这个是首页")
index()
装饰器用法1
# 有个相加的方法 在这个基础上加一个相乘的 方法 可以用装饰器实现
def add(func):
def fun(a,b):
print("相乘:",a * b)
func(a,b)
return fun342
@add
def add_sum(a, b):
print("相加:" , a + b)
add_sum(11,22)
装饰器装饰类
def add(func):
def fun(*args, **kwargs):
print("参数:登录")
return func(*args, **kwargs) # 装饰器装饰类的时候 这个return必须写
return fun
@add
class Myclass:
def __init__(self):
print("执行class功能")
pass
myclass = Myclass()
print(myclass)
如何定义一个函数运行时间的装饰器
def time_count(func):
def count_time(*args, **keyword):
start_time = time.time()
func(*args, **keyword)
end_time = time.time()
print("函数运行时间:", end_time - start_time)
return count_time
@time_count
def func1():
print("func1")
for i in range(10000):
i += 1
funcc = func1()
print(funcc)
定义一个检查登录的装饰器
with open ( "user.txt" ) as f:
users = eval ( f. read( ) )
print ( users)
def login_check ( func) :
def ado ( ) :
while not users[ 'token' ] :
print ( '------登录页面-----' )
username = input ( "账号:" )
password = input ( "密码:" )
if users[ "username" ] == username and users[ "password" ] == password:
users[ "token" ] = True
func( )
else :
func( )
return ado
@login_check
def good_list ( ) :
print ( "已经登录可以获取商品列表" )
good = good_list( )
多个装饰器装饰一个函数
import time
with open ( "user.txt" ) as f:
users = eval ( f. read( ) )
print ( users)
def login_check ( func) :
def ado ( ) :
while not users[ 'token' ] :
print ( '------登录页面-----' )
username = input ( "账号:" )
password = input ( "密码:" )
if users[ "username" ] == username and users[ "password" ] == password:
users[ "token" ] = True
func( )
else :
func( )
return ado
def time_count ( func) :
def count_time ( * args, ** keyword) :
start_time = time. time( )
func( * args, ** keyword)
end_time = time. time( )
print ( "函数运行时间:" , end_time - start_time)
return count_time
@login_check
@time_count
def good_list ( ) :
time. sleep( 2 )
print ( "已经登录可以获取商品列表" )
good = good_list( )
python 3个 内置装饰器
class MyTest ( object ) :
def __init__ ( self, name) :
self. name = name
@classmethod
def add ( cls) :
print ( "add" )
print ( 'add中的self' , cls)
@staticmethod
def sub ( ) :
print ( 'sub中的self' )
@property
def read_attr ( self) :
print ( '装饰完了知识改方法可以像属性被调用' , self)
return "18"
t = MyTest( 'musen' )
t. name = "张Sam"
print ( t. name)
print ( t. read_attr)
t. add( )
t. sub( )
MyTest. add( )
MyTest. sub( )
attr = MyTest. read_attr
attr1 = t. read_attr
print ( attr)
print ( attr1)
魔术方法
__init__
![ 在这里插入图片描述] ( https: // img- blog. csdnimg. cn/ 372ab8a300f74317879afa4a8e6f4b7c. png
init( ) - 初始化方法,类的实例化时自动调用,用于初始化对象的属性。
str ( ) - 字符串表示方法,将对象转换为字符串,常用于打印输出。
repr ( ) - 对象表示方法,返回对象的代码表示,通常用于调试和交互式环境。
add( ) - 加法方法,定义对象相加的行为。
eq( ) - 等于方法,定义对象相等的判断方式。
len ( ) - 长度方法,返回对象的长度。
getitem( ) - 获取元素方法,用于获取集合类型对象的元素。
setitem( ) - 设置元素方法,用于设置集合类型对象的元素。
delitem( ) - 删除元素方法,用于删除集合类型对象的元素。
call( ) - 可调用方法,使对象可以像函数一样被调用。
getattr ( ) - 获取属性方法,当访问不存在的属性时自动调用。
setattr ( ) - 设置属性方法,用于设置对象的属性。
delattr ( ) - 删除属性方法,用于删除对象的属性。
单利模式
class MyTest ( object ) :
__instance = None
def __new__ ( cls, * args, ** kwargs) :
print ( "这个是new方法" )
if not cls. __instance:
cls. __instance = object . __new__( cls)
return cls. __instance
else :
return cls. __instance
t1 = MyTest( )
t1. name = "MUSAN"
t2 = MyTest( )
print ( 't1' , t1. name)
print ( 't2' , t2. name)
print ( id ( t1) == id ( t2) )
手写 上下文管理器
with open ( "text.txt" , mode= "w+" , encoding= "utf8" ) as f:
f. write( "写入功能" )
class FileOpener :
def __init__ ( self, file_path, file_method) :
self. file_path = file_path
self. file_method = file_method
print ( "开始" )
def __enter__ ( self) :
self. file = open ( self. file_path, self. file_method , encoding= 'utf8' )
print ( "进入" )
return self. file
def __exit__ ( self, exc_type, exc_val, exc_tb) :
self. file . close( )
print ( "退出" )
with FileOpener( 'text.txt' , 'w+' ) as f:
f. write( "是飒飒大的" )
with FileOpener( 'text.txt' , 'r' ) as f:
content = f. read( )
print ( content)
python 伪多态的实现与理解 也就是常说的鸭子类型 python 类中传参不限制base类型 所以不存在真正意义上的多态
class Animal ( object ) :
def run ( self) :
print ( "-------annimal------走路---" )
class Cat ( Animal) :
def run ( self) :
print ( "-------Cat------爬树---" )
class Dog ( Animal) :
def run ( self) :
print ( "-------Dog------爬树---" )
class Pig ( Animal) :
pass
a_obj = Animal( )
c = Cat( )
d = Dog( )
p = Pig( )
def func ( base) :
base. run( )
func( a_obj)
func( d)
func( c)
func( p)
私有属性
class Test ( ) :
attr = 1000
_attr1 = 2000
__attr2 = 4000
def func ( self) :
pass
test = Test( )
print ( Test. attr)
print ( Test. _attr1)
print ( test. attr)
print ( test. _attr1)
print ( test. _Test__attr2)
print ( Test. __dict__)
python 中 __slots __ 使用 节省内存空间
class Base ( object ) :
__slots__ = [ "name" , "age" ]
def func ( self) :
pass
base = Base( )
base. name = "张三"
base. age = "18"
base. sex = "男"
print ( base. name)
print ( base. age)
pyhton 中ORM 的应用
from sqlalchemy import create_engine, Column, Integer, String
from sqlalchemy. ext. declarative import declarative_base
from sqlalchemy. orm import sessionmaker
Base = declarative_base( )
class User ( Base) :
__tablename__ = 'users'
id = Column( Integer, primary_key= True )
name = Column( String)
age = Column( Integer)
engine = create_engine( 'sqlite:///example.db' )
Base. metadata. create_all( engine)
Session = sessionmaker( bind= engine)
session = Session( )
new_user = User( name= '张三' , age= 25 )
session. add( new_user)
session. commit( )
users = session. query( User) . filter_by( name= '张三' ) . all ( )
for user in users:
print ( user. id , user. name, user. age)
session. close( )