一般情况下,如果一个函数结束,函数的内部所有东西都会释放掉,还给内存,局部变量都会消失。但是闭包是一种特殊情况,如果外函数在结束的时候发现有自己的临时变量将来会在内部函数中用到,就把这个临时变量绑定给了内部函数,然后自己再结束
def line_6(k, b):
def create_y(x):
print(k*x + b)
return create_y
line_6_1 = line_6(1, 2)
line_6_1(2)
class Line5(object):
def __init__(self, k, b):
self.k = k
self.b = b
def __call__(self, x):
print(self.k * x + self.b)
line_5_1=Line5(1, 2)
line_5_1(0)
def set_func(func):
def call_func():
print("---quan xian yanzheng 1")
print("----quanxian yanzheng 2")
func()
return call_func
def test1():
print("----------test1------")
test1 = set_func(test1)
print("*" * 30)
test1()
装饰器
def set_func(func):
def call_func():
print("---quan xian yanzheng 1")
print("----quanxian yanzheng 2")
func()
return call_func
@set_func #等价于test1=set_func(test1)
def test1():
print("----------#test1------")
#test1 = set_func(test1)
print("*" * 30)
test1()
使用type创建类,type还有一种完全不同的功能,动态的创建类。type可以接受一个类作为参数,然后返回一个类,
类是有元类创建的
test33 = type("Test2",(),{"num":100,"num2":30})
help(test33)
class ModelMetaclass(type):
def __new__(cls, name, bases, attrs):
mappings = dict()
for k, v in attrs.items():
if isinstance(v, tuple):
print("found mappings %s===> %s" % (k, v))
mappings[k] = v
for k in mappings.keys():
attrs.pop(k)
attrs["__mappings__"] = mappings
attrs["__table__"] = name
return type.__new__(cls, name, bases, attrs)
class User(metaclass=ModelMetaclass):
uid = ('uid', "int unsigned")
name = ('username', "varchar(30)")
email = ('email', "varchar(30)")
password = ('password',"varchar(39)")
def __init__(self, **kwargs):
for name, value in kwargs.items():
setattr(self, name, value)
def save(self):
fields = []
args = []
for k, v in self.__mappings__.items():
fields.append(v[0])
args.append(getattr(self, k, None))
# sql = 'insert into %s (%s) values (%s)' % (self.__table__, ','.join(fie
lds), ','.join([str(i) for i in args]))
args_temp = list()
for temp in args:
if isinstance(temp, int):
args_temp.append(str(temp))
elif isinstance(temp, str):
args_temp.append("""'%s'""" % temp)
sql = 'insert into %s (%s) values (%s)' % (self.__table__, ','.join(fiel
ds), ','.join(args_temp))
print('sql: %s' % sql)
u = User(uid=12345, name="zhaoyongfei", email="[email protected]", password="my
-pwd")
u.save()
安装虚拟环境(pip方式)
命令:
mkvirtualenv 项目名 ------------#创建虚拟环境 -p 指定python版本
workon 虚拟环境名字 ----------进入虚拟环境
deactivate -----------退出虚拟
deactivate -------------------------虚拟环境内部执行,退出虚拟环境
django-admin startproject 项目名--------创建django项目
pip freeeze > requirements.txt
pip install -r requirements.txt
-----------------------------------------------------------------------------------------------------------------
python manage.py runserver 启动项目
pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pandas----------指定源下载文件
阿里云 http://mirrors.aliyun.com/pypi/simple/
中国科技大学 https://pypi.mirrors.ustc.edu.cn/simple/
豆瓣(douban) http://pypi.douban.com/simple/
清华大学 https://pypi.tuna.tsinghua.edu.cn/simple/
中国科学技术大学 http://pypi.mirrors.ustc.edu.cn/simple/
Linux下,修改 ~/.pip/pip.conf (没有就创建一个文件夹及文件。文件夹要加“.”,表示是隐藏文件夹)
内容如下:
[global]
index-url = https://pypi.tuna.tsinghua.edu.cn/simple
[install]
trusted-host = https://pypi.tuna.tsinghua.edu.cn
---------------------------------------------------------------------------------------------------------------------
django-admin startproject 项目名
python manage.py startapp 应用名
settings.py中INSTALLED_APPS=[...]设置
连接数据库:settings.py中DATABASES
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'python',
'HOST': 'localhost',
'PORT': 3306,
'USER': 'root',
'PASSWORD': 'root'
}
}
安装pymysql 模块,项目同名__init__.py文件导入
import pymysql
pymysql.install_as_MySQLdb()
python manage.py makemigrations #生成迁移文件
python manage.py migrate #执行迁移文件
#执行命令时汇报错,有可能
1)AttributeError: 'str' object has no attribute 'decode'
/home/python/Desktop/ysten/Incrementserver/lib/python3.7/site-packages/Django-2.2-py3.7.egg/django/db/backends/my
打开 operations.py
找到错误代码(line146):query = query.encode(errors='replace')
解决方法:把decode改为encode即可。
2)Django2.2报错 django.core.exceptions.ImproperlyConfigured: mysqlclient 1.3.13 or newer is required; you have 0.9.3.
version = Database.version_info
if version < (1, 3, 13):
raise ImproperlyConfigured('mysqlclient 1.3.13 or newer is required; you have %s.' % Database.__version__)
base.py 注释调以上内容
参考:https://www.cnblogs.com/dbf-/p/10838112.html
https://blog.csdn.net/myli_binbin/article/details/90178345
有工具编辑比教方便
在以上的基础上操作以ia步骤
b2.book_date = date(1990,10,10) # b.title="tainlogn babu"
b.title="tainlogn babu"
b.save()#保存之数据库
查询#b2 = BookInfo.objects.get(id=1)
selenium,用代码模拟操作页面---打码