今日内容概要

  • 登录注册模态框分析
  • 登录注册前端页面
  • 腾讯短信功能二次封装
  • 短信验证码接口
  • 短信登录接口
  • 短信注册接口

今日内容详细

登录注册模态框分析

# 如果是跳转新的页面
    -路由中配置一个路由
    -写一个视图组件
# 弹窗,盖在主页上---> 模态框

Login.vue

<template>
  <div class="login">
    <span @click="handleClose">X</span>
  </div>
</template>

<script>
export default {
  name: "Login",
  methods:{
    handleClose(){
      this.$emit('close')
    }
  }
}
</script>

<style scoped>
.login {
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 10;
  background-color: rgba(0, 0, 0, 0.5);
}
</style>

Header.vue

<div class="right-part">
    <div>
        <span @click="goLogin">登录</span>
        <span class="line">|</span>
        <span>注册</span>
    </div>
    <Login v-if="loginShow" @close="closeLogin"></Login>
</div>

<script>
 export default {
  name: "Header",
  data() {
    return {
      url_path: sessionStorage.url_path || '/',
      loginShow: false
    }
  },
  methods: {
    goPage(url_path) {
      // 已经是当前路由就没有必要重新跳转
      if (this.url_path !== url_path) {
        // 传入的参数,如果不等于当前路径,就跳转
        this.$router.push(url_path)
      }
      sessionStorage.url_path = url_path;
    },
    goLogin() {
      this.loginShow = true
    },
    closeLogin() {
      this.loginShow = false
    }
  },
  created() {
    sessionStorage.url_path = this.$route.path
    this.url_path = this.$route.path
  },
  components: {
    Login
  }
}
</script>

登录注册前端页面

Header.vue

<template>
  <div class="header">
    <div class="slogan">
      <p>老男孩IT教育 | 帮助有志向的年轻人通过努力学习获得体面的工作和生活</p>
    </div>
    <div class="nav">
      <ul class="left-part">
        <li class="logo">
          <router-link to="/">
            <img src="../assets/img/head-logo.svg" alt="">
          </router-link>
        </li>
        <li class="ele">
          <span @click="goPage('/free-course')" :class="{active: url_path === '/free-course'}">免费课</span>
        </li>
        <li class="ele">
          <span @click="goPage('/actual-course')" :class="{active: url_path === '/actual-course'}">实战课</span>
        </li>
        <li class="ele">
          <span @click="goPage('/light-course')" :class="{active: url_path === '/light-course'}">轻课</span>
        </li>
      </ul>

      <div class="right-part">
        <div>
          <span @click="put_login">登录</span>
          <span class="line">|</span>
          <span @click="put_register">注册</span>
        </div>
        <Login v-if="is_login" @close="close_login" @go="put_register"></Login>
        <Register v-if="is_register" @close="close_register" @go="put_login"></Register>
      </div>
    </div>
  </div>
</template>

<script>
import Login from "@/components/Login";
import Register from "@/components/Register";

export default {
  name: "Header",
  data() {
    return {
      url_path: sessionStorage.url_path || '/',
      is_login: false,
      is_register: false,
    }
  },
  methods: {
    goPage(url_path) {
      // 已经是当前路由就没有必要重新跳转
      if (this.url_path !== url_path) {
        // 传入的参数,如果不等于当前路径,就跳转
        this.$router.push(url_path)
      }
      sessionStorage.url_path = url_path;
    },
    goLogin() {
      this.loginShow = true
    },
    put_login() {
      this.is_login = true;
      this.is_register = false;
    },
    put_register() {
      this.is_login = false;
      this.is_register = true;
    },
    close_login() {
      this.is_login = false;
    },
    close_register() {
      this.is_register = false;
    }
  },
  created() {
    sessionStorage.url_path = this.$route.path
    this.url_path = this.$route.path
  },
  components: {
    Login,
    Register
  }
}
</script>

<style scoped>
.header {
  background-color: white;
  box-shadow: 0 0 5px 0 #aaa;
}
.header:after {
  content: "";
  display: block;
  clear: both;
}
.slogan {
  background-color: #eee;
  height: 40px;
}
.slogan p {
  width: 1200px;
  margin: 0 auto;
  color: #aaa;
  font-size: 13px;
  line-height: 40px;
}
.nav {
  background-color: white;
  user-select: none;
  width: 1200px;
  margin: 0 auto;

}
.nav ul {
  padding: 15px 0;
  float: left;
}
.nav ul:after {
  clear: both;
  content: '';
  display: block;
}
.nav ul li {
  float: left;
}
.logo {
  margin-right: 20px;
}
.ele {
  margin: 0 20px;
}
.ele span {
  display: block;
  font: 15px/36px '微软雅黑';
  border-bottom: 2px solid transparent;
  cursor: pointer;
}
.ele span:hover {
  border-bottom-color: orange;
}
.ele span.active {
  color: orange;
  border-bottom-color: orange;
}
.right-part {
  float: right;
}
.right-part .line {
  margin: 0 10px;
}
.right-part span {
  line-height: 68px;
  cursor: pointer;
}
</style>

Login.vue

<template>
  <div class="login">
    <div class="box">
      <i class="el-icon-close" @click="close_login"></i>
      <div class="content">
        <div class="nav">
          <span :class="{active: login_method === 'is_pwd'}"
                @click="change_login_method('is_pwd')">密码登录</span>
          <span :class="{active: login_method === 'is_sms'}"
                @click="change_login_method('is_sms')">短信登录</span>
        </div>
        <el-form v-if="login_method === 'is_pwd'">
          <el-input
              placeholder="用户名/手机号/邮箱"
              prefix-icon="el-icon-user"
              v-model="username"
              clearable>
          </el-input>
          <el-input
              placeholder="密码"
              prefix-icon="el-icon-key"
              v-model="password"
              clearable
              show-password>
          </el-input>
          <el-button type="primary">登录</el-button>
        </el-form>
        <el-form v-if="login_method === 'is_sms'">
          <el-input
              placeholder="手机号"
              prefix-icon="el-icon-phone-outline"
              v-model="mobile"
              clearable
              @blur="check_mobile">
          </el-input>
          <el-input
              placeholder="验证码"
              prefix-icon="el-icon-chat-line-round"
              v-model="sms"
              clearable>
            <template slot="append">
              <span class="sms" @click="send_sms">{{ sms_interval }}</span>
            </template>
          </el-input>
          <el-button type="primary">登录</el-button>
        </el-form>
        <div class="foot">
          <span @click="go_register">立即注册</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "Login",
  data() {
    return {
      username: '',
      password: '',
      mobile: '',
      sms: '',
      login_method: 'is_pwd',
      sms_interval: '获取验证码',
      is_send: false,
    }
  },
  methods: {
    close_login() {
      this.$emit('close')
    },
    go_register() {
      this.$emit('go')
    },
    change_login_method(method) {
      this.login_method = method;
    },
    check_mobile() {
      if (!this.mobile) return;
      if (!this.mobile.match(/^1[3-9][0-9]{9}$/)) {
        this.$message({
          message: '手机号有误',
          type: 'warning',
          duration: 1000,
          onClose: () => {
            this.mobile = '';
          }
        });
        return false;
      }
      this.is_send = true;
    },
    send_sms() {
      if (!this.is_send) return;
      this.is_send = false;
      let sms_interval_time = 60;
      this.sms_interval = "发送中...";
      let timer = setInterval(() => {
        if (sms_interval_time <= 1) {
          clearInterval(timer);
          this.sms_interval = "获取验证码";
          this.is_send = true; // 重新回复点击发送功能的条件
        } else {
          sms_interval_time -= 1;
          this.sms_interval = `${sms_interval_time}秒后再发`;
        }
      }, 1000);
    }
  }
}
</script>

<style scoped>
.login {
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 10;
  background-color: rgba(0, 0, 0, 0.3);
}
.box {
  width: 400px;
  height: 420px;
  background-color: white;
  border-radius: 10px;
  position: relative;
  top: calc(50vh - 210px);
  left: calc(50vw - 200px);
}
.el-icon-close {
  position: absolute;
  font-weight: bold;
  font-size: 20px;
  top: 10px;
  right: 10px;
  cursor: pointer;
}
.el-icon-close:hover {
  color: darkred;
}
.content {
  position: absolute;
  top: 40px;
  width: 280px;
  left: 60px;
}
.nav {
  font-size: 20px;
  height: 38px;
  border-bottom: 2px solid darkgrey;
}
.nav > span {
  margin: 0 20px 0 35px;
  color: darkgrey;
  user-select: none;
  cursor: pointer;
  padding-bottom: 10px;
  border-bottom: 2px solid darkgrey;
}
.nav > span.active {
  color: black;
  border-bottom: 3px solid black;
  padding-bottom: 9px;
}
.el-input, .el-button {
  margin-top: 40px;
}
.el-button {
  width: 100%;
  font-size: 18px;
}
.foot > span {
  float: right;
  margin-top: 20px;
  color: orange;
  cursor: pointer;
}
.sms {
  color: orange;
  cursor: pointer;
  display: inline-block;
  width: 70px;
  text-align: center;
  user-select: none;
}
</style>

Register.vue

<template>
  <div class="register">
    <div class="box">
      <i class="el-icon-close" @click="close_register"></i>
      <div class="content">
        <div class="nav">
          <span class="active">新用户注册</span>
        </div>
        <el-form>
          <el-input
              placeholder="手机号"
              prefix-icon="el-icon-phone-outline"
              v-model="mobile"
              clearable
              @blur="check_mobile">
          </el-input>
          <el-input
              placeholder="密码"
              prefix-icon="el-icon-key"
              v-model="password"
              clearable
              show-password>
          </el-input>
          <el-input
              placeholder="验证码"
              prefix-icon="el-icon-chat-line-round"
              v-model="sms"
              clearable>
            <template slot="append">
              <span class="sms" @click="send_sms">{{ sms_interval }}</span>
            </template>
          </el-input>
          <el-button type="primary">注册</el-button>
        </el-form>
        <div class="foot">
          <span @click="go_login">立即登录</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "Register",
  data() {
    return {
      mobile: '',
      password: '',
      sms: '',
      sms_interval: '获取验证码',
      is_send: false,
    }
  },
  methods: {
    close_register() {
      this.$emit('close', false)
    },
    go_login() {
      this.$emit('go')
    },
    check_mobile() {
      if (!this.mobile) return;
      if (!this.mobile.match(/^1[3-9][0-9]{9}$/)) {
        this.$message({
          message: '手机号有误',
          type: 'warning',
          duration: 1000,
          onClose: () => {
            this.mobile = '';
          }
        });
        return false;
      }
      this.is_send = true;
    },
    send_sms() {
      if (!this.is_send) return;
      this.is_send = false;
      let sms_interval_time = 60;
      this.sms_interval = "发送中...";
      let timer = setInterval(() => {
        if (sms_interval_time <= 1) {
          clearInterval(timer);
          this.sms_interval = "获取验证码";
          this.is_send = true; // 重新回复点击发送功能的条件
        } else {
          sms_interval_time -= 1;
          this.sms_interval = `${sms_interval_time}秒后再发`;
        }
      }, 1000);
    }
  }
}
</script>

<style scoped>
.register {
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 10;
  background-color: rgba(0, 0, 0, 0.3);
}
.box {
  width: 400px;
  height: 480px;
  background-color: white;
  border-radius: 10px;
  position: relative;
  top: calc(50vh - 240px);
  left: calc(50vw - 200px);
}
.el-icon-close {
  position: absolute;
  font-weight: bold;
  font-size: 20px;
  top: 10px;
  right: 10px;
  cursor: pointer;
}
.el-icon-close:hover {
  color: darkred;
}
.content {
  position: absolute;
  top: 40px;
  width: 280px;
  left: 60px;
}
.nav {
  font-size: 20px;
  height: 38px;
  border-bottom: 2px solid darkgrey;
}
.nav > span {
  margin-left: 90px;
  color: darkgrey;
  user-select: none;
  cursor: pointer;
  padding-bottom: 10px;
  border-bottom: 2px solid darkgrey;
}
.nav > span.active {
  color: black;
  border-bottom: 3px solid black;
  padding-bottom: 9px;
}
.el-input, .el-button {
  margin-top: 40px;
}
.el-button {
  width: 100%;
  font-size: 18px;
}
.foot > span {
  float: right;
  margin-top: 20px;
  color: orange;
  cursor: pointer;
}
.sms {
  color: orange;
  cursor: pointer;
  display: inline-block;
  width: 70px;
  text-align: center;
  user-select: none;
}
</style>

腾讯短信功能二次封装

封装v3版本

# sdk:https://cloud.tencent.com/document/product/382/43196#
# 使用步骤:
    -下载模块:pip3 install tencentcloud-sdk-python

把发送短信封装成包

# 后期别的项目,也要使用发送短信----》只要把包copy到项目中即可

# 封装包:
-目录结构
    send_tx_sms  #包名
    __init__.py
    settings.py #配置文件
    sms.py      # 核心文件

libs/send_tx_sms/__ init__

from .sms import get_code, send_sms_by_mobile

libs/send_tx_sms/settings.py

# 发送短信相关的配置信息

SECRET_ID = 'AKIDa3NUTYS9kEbpwrpdHoAORgmkwNxJTcfa'
SECRET_KEY = '6f4LVWN2Wos48zc3PYUGqESWNzObDcol'
APP_ID = '1400763280'
SING_NAME = 'wjlit个人公众号'
TEMPLATE_ID = '1603837'

libs/send_tx_sms/sms.py

# 核心代码

import random
from tencentcloud.common import credential
from tencentcloud.common.exception.tencent_cloud_sdk_exception import TencentCloudSDKException
# 导入对应产品模块的client models。
from tencentcloud.sms.v20210111 import sms_client, models
# 导入可选配置类
from tencentcloud.common.profile.client_profile import ClientProfile
from tencentcloud.common.profile.http_profile import HttpProfile
from . import settings

# 获取n位随机组合的验证码的函数
def get_code(num=4):
    code = ''
    for i in range(num):
        random_num = random.randint(0, 9)
        code += str(random_num)
    return code

# 发送短信函数
def send_sms_by_mobile(mobile, code):
    try:
        # 必要步骤:
        # 实例化一个认证对象,入参需要传入腾讯云账户密钥对secretId,secretKey。
        # 这里采用的是从环境变量读取的方式,需要在环境变量中先设置这两个值。
        # 你也可以直接在代码中写死密钥对,但是小心不要将代码复制、上传或者分享给他人,
        # 以免泄露密钥对危及你的财产安全。
        # SecretId、SecretKey 查询: https://console.cloud.tencent.com/cam/capi
        cred = credential.Credential(settings.SECRET_ID, settings.SECRET_KEY)
        # cred = credential.Credential(
        #     os.environ.get(""),
        #     os.environ.get("")
        # )
        # 实例化一个http选项,可选的,没有特殊需求可以跳过。
        httpProfile = HttpProfile()
        # 如果需要指定proxy访问接口,可以按照如下方式初始化hp(无需要直接忽略)
        # httpProfile = HttpProfile(proxy="http://用户名:密码@代理IP:代理端口")
        httpProfile.reqMethod = "POST"  # post请求(默认为post请求)
        httpProfile.reqTimeout = 6000  # 请求超时时间,单位为秒(默认60秒)
        httpProfile.endpoint = "sms.tencentcloudapi.com"  # 指定接入地域域名(默认就近接入)

        # 非必要步骤:
        # 实例化一个客户端配置对象,可以指定超时时间等配置
        clientProfile = ClientProfile()
        clientProfile.signMethod = "TC3-HMAC-SHA256"  # 指定签名算法
        clientProfile.language = "en-US"
        clientProfile.httpProfile = httpProfile

        # 实例化要请求产品(以sms为例)的client对象
        # 第二个参数是地域信息,可以直接填写字符串ap-guangzhou,支持的地域列表参考 https://cloud.tencent.com/document/api/382/52071#.E5.9C.B0.E5.9F.9F.E5.88.97.E8.A1.A8
        client = sms_client.SmsClient(cred, "ap-guangzhou", clientProfile)

        # 实例化一个请求对象,根据调用的接口和实际情况,可以进一步设置请求参数
        # 你可以直接查询SDK源码确定SendSmsRequest有哪些属性可以设置
        # 属性可能是基本类型,也可能引用了另一个数据结构
        # 推荐使用IDE进行开发,可以方便的跳转查阅各个接口和数据结构的文档说明
        req = models.SendSmsRequest()

        # 基本类型的设置:
        # SDK采用的是指针风格指定参数,即使对于基本类型你也需要用指针来对参数赋值。
        # SDK提供对基本类型的指针引用封装函数
        # 帮助链接:
        # 短信控制台: https://console.cloud.tencent.com/smsv2
        # 腾讯云短信小助手: https://cloud.tencent.com/document/product/382/3773#.E6.8A.80.E6.9C.AF.E4.BA.A4.E6.B5.81

        # 短信应用ID: 短信SdkAppId在 [短信控制台] 添加应用后生成的实际SdkAppId,示例如1400006666
        # 应用 ID 可前往 [短信控制台](https://console.cloud.tencent.com/smsv2/app-manage) 查看
        req.SmsSdkAppId = settings.APP_ID
        # 短信签名内容: 使用 UTF-8 编码,必须填写已审核通过的签名
        # 签名信息可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-sign) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-sign) 的签名管理查看
        req.SignName = settings.SING_NAME
        # 模板 ID: 必须填写已审核通过的模板 ID
        # 模板 ID 可前往 [国内短信](https://console.cloud.tencent.com/smsv2/csms-template) 或 [国际/港澳台短信](https://console.cloud.tencent.com/smsv2/isms-template) 的正文模板管理查看
        req.TemplateId = settings.TEMPLATE_ID
        # 模板参数: 模板参数的个数需要与 TemplateId 对应模板的变量个数保持一致,,若无模板参数,则设置为空
        req.TemplateParamSet = [code, '5']
        # 下发手机号码,采用 E.164 标准,+[国家或地区码][手机号]
        # 示例如:+8613711112222, 其中前面有一个+号 ,86为国家码,13711112222为手机号,最多不要超过200个手机号
        req.PhoneNumberSet = ["+86" + mobile, ]
        # 用户的 session 内容(无需要可忽略): 可以携带用户侧 ID 等上下文信息,server 会原样返回
        req.SessionContext = ""
        # 短信码号扩展号(无需要可忽略): 默认未开通,如需开通请联系 [腾讯云短信小助手]
        req.ExtendCode = ""
        # 国际/港澳台短信 senderid(无需要可忽略): 国内短信填空,默认未开通,如需开通请联系 [腾讯云短信小助手]
        req.SenderId = ""

        resp = client.SendSms(req)

        # 输出json格式的字符串回包
        print(type(resp.to_json_string(indent=2)))
        # if dict(resp.to_json_string(indent=1)).get('SendStatusSet')[0].get('Code') == 'Ok':
        return True
    except TencentCloudSDKException as err:
        return False

短信验证码接口

请求地址:http://127.0.0.1:8000/api/v1/userinfo/user/send_sms/?mobile=xxx
请求方式:get
请求参数:{"mobile":"xxx", "code":"xx"}

views.py

class UserView(ViewSet):
    @action(methods=['GET'], detail=False)
    def send_sms(self, request):
        mobile = request.query_params.get('mobile')
        if re.match(r'^1[3-9][0-9]{9}$', mobile):
            code = get_code()
            print(code)
            # 放在内存中了,只要重启就没了----》后期学完redis,放到redis中,重启项目,还在
            cache.set('sms_code_%s' % mobile, code)
            # cache.get('sms_code_%s'%mobile)
            res = send_sms_by_mobile(mobile, code)
            if res:
                return APIResponse(msg='发送短信成功')
            else:
                raise APIException('发送短信失败')
        else:
            raise APIException('手机号不符合要求')

短信验证码登录接口

请求地址:http://127.0.0.1:8000/api/v1/userinfo/user/mobile_login/
请求方式:post
请求参数:{"mobile":"xxx", "code":"xx"}

user/serializer.py

from rest_framework import serializers
from .models import UserInfo
import re
from rest_framework.exceptions import ValidationError, APIException
from django.core.cache import cache
from rest_framework_jwt.settings import api_settings

jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER


class ValidateGetToken(serializers.ModelSerializer):
    def _get_user(self, attrs):
        return attrs

    def _get_token(self, user):
        try:
            payload = jwt_payload_handler(user)
            token = jwt_encode_handler(payload)
            return token
        except Exception as e:
            raise ValidationError(str(e))

    def validate(self, attrs):
        user = self._get_user(attrs)
        token = self._get_token(user)
        self.context['token'] = token
        self.context['username'] = user.username
        self.context['icon'] = 'http://127.0.0.1:8000/media/' + str(user.icon)
        return attrs

class UserMulLoginSerializer(ValidateGetToken):
    username = serializers.CharField()

    class Meta:
        model = UserInfo
        fields = ['username', 'password']

    def _get_user(self, attrs):
        try:
            username = attrs.get('username')
            password = attrs.get('password')
            if re.match(r'^1[3-9][0-9]{9}$', username):
                user = UserInfo.objects.get(mobile=username)
            elif re.match(r'^.+@.+$', username):
                user = UserInfo.objects.get(email=username)
            else:
                user = UserInfo.objects.get(username=username)
            if user.check_password(password):
                return user
            else:
                raise ValidationError('密码错误')
        except Exception:
            raise APIException('用户名或密码错误')

class UserMobileLoginSerializer(ValidateGetToken):
    code = serializers.CharField()  # code 不是UserInfo表的字段,一定要重写一下
    mobile = serializers.CharField()

    class Meta:
        model = UserInfo
        fields = ['mobile', 'code']

    def _get_user(self, attrs):
        mobile = attrs.get('mobile')
        code = attrs.get('code')
        # 校验code是否正确
        old_code = cache.get('sms_code_%s' % mobile)
        cache.set('sms_code_%s' % mobile, '')  # 验证码用过了要清除
        if code == old_code:  # 万能验证码,在测试阶段,测试用的
            user = UserInfo.objects.filter(mobile=mobile).first()
            return user
        raise APIException('验证码错误')

user/views.py

from django.shortcuts import render
from rest_framework.viewsets import ViewSet
from .serializer import UserMulLoginSerializer, UserMobileLoginSerializer
from utils.response import APIResponse
from rest_framework.decorators import action
from .models import UserInfo
from rest_framework.exceptions import APIException
from libs.send_tx_sms import get_code, send_sms_by_mobile
import re
from django.core.cache import cache

class UserView(ViewSet):

    def get_serializer(self, data):
        if self.action == 'mul_login':
            return UserMulLoginSerializer(data=data)
        else:
            return UserMobileLoginSerializer(data=data)

    def common_login(self, request):
        ser = self.get_serializer(data=request.data)
        ser.is_valid(raise_exception=True)
        token = ser.context.get('token')
        username = ser.context.get('username')
        icon = ser.context.get('icon')
        return APIResponse(token=token, username=username, icon=icon)

    @action(methods=['POST'], detail=False)
    def mul_login(self, request):
        return self.common_login(request)

    @action(methods=['POST'], detail=False)
    def mobile_login(self, request):
        return self.common_login(request)

    @action(methods=['GET'], detail=False)
    def mobile(self, request):
        try:
            mobile = request.query_params.get('mobile')
            UserInfo.objects.get(mobile=mobile)
            return APIResponse(msg='手机号存在')
        except Exception as e:
            raise APIException('手机号不存在')

    @action(methods=['GET'], detail=False)
    def send_sms(self, request):
        mobile = request.query_params.get('mobile')
        if re.match(r'^1[3-9][0-9]{9}$', mobile):
            code = get_code()
            print(code)
            # 放在内存中了,只要重启就没了----》后期学完redis,放到redis中,重启项目,还在
            cache.set('sms_code_%s' % mobile, code)
            res = send_sms_by_mobile(mobile, code)
            if res:
                return APIResponse(msg='发送短信成功')
            else:
                raise APIException('发送短信失败')
        else:
            raise APIException('手机号不符合要求')

扩展知识

# python的深浅拷贝
最直观的理解就是:
1.深拷贝,拷贝的程度深,自己新开辟了一块内存,将被拷贝内容全部拷贝过来了;
2.浅拷贝,拷贝的程度浅,只拷贝原数据的首地址,然后通过原数据的首地址,去获取内容。
两者的优缺点对比:
(1)深拷贝拷贝程度高,将原数据复制到新的内存空间中。改变拷贝后的内容不影响原数据内容。但是深拷贝耗时长,且占用内存空间。
(2)浅拷贝拷贝程度低,只复制原数据的地址。其实是将副本的地址指向原数据地址。修改副本内容,是通过当前地址指向原数据地址,去修改。所以修改副本内容会影响到原数据内容。但是浅拷贝耗时短,占用内存空间少。

当内层为可变数据类型时,深拷贝后内层外层地址均发生改变。当内层为不可变数据类型时,外层不管是可变还是不可变数据类型,使用深拷贝,都不会改变内层地址,只会在外层为可变数据类型时,改变外层地址。
使用浅拷贝是只能在外层数据类型为可变数据类型时,才能改变外层地址。而内层地址,无论是否为可变数据类型还是不可变数据类型,使用浅拷贝都不会改变内层数据类型地址。

# __new__和__init__的区别
__new__()用于创建实例,而__init__()则负责初始化实例
__new__方法:类级别的方法 、 __init__方法:实例级别的方法
1、__new__ 至少要有一个参数cls,代表当前类,此参数在实例化时由Python解释器自动识别
2、__new__ 必须要有返回值,返回实例化出来的实例,可以return 父类__new__出来的实例 或者直接是object的__new__出来的实例
3、__int__ 有一个参数self,就是这个__new__返回的实例, __init__在__new__的基础上可以完成一些其它初始化的动作,__init__不需要返回值
4、如果__new__创建的是当前类的实例,会自动调用init函数通过return调用的__new__函数的第一个参数cls来保证是当前类实例;如果是其它类的类名实际创建返回的也是其他类的实例,不会调用当前类的__init__,也不会调用其他类的__init__

# python 是值传递还是引用传递
Python参数传递统一使用的是引用传递方式。因为Python对象分为可变对象(list,dict,set等)和不可变对象(number,string,tuple等);
当传递的参数是可变对象的引用时,因为可变对象的值可以修改,因此可以通过修改参数值而修改原对象,这类似于C语言中的引用传递;
当传递的参数是不可变对象的引用时,虽然传递的是引用,参数变量和原变量都指向同一内存地址,但是不可变对象无法修改,所以参数的重新赋值不会影响原对象,这类似于C语言中的值传递。

# python 可变与不可变
不可变类型的变量在第一次赋值声明的时候,会在内存中开辟一块空间,用来存储这个变量被赋予的值,变量被声明后,变量的值就与开辟的内存空间绑定,我们不能修改存储在内存中的值,当我们想给此变量赋新值时,会开辟一块新的内存空间保存新的值。
不可变数据类型的值变化,地址也会变。

可变类型的变量在第一次赋值声明的时候,也会在内存中开辟一块空间,用来存储这个变量被赋予的值。我们能修改存储在内存中的值,当该变量的值发生了改变,它对应的内存地址不发生改变。
可变数据类型变量中的值变化,地址不会变。若对变量进行重新赋值,则变量的地址也会改变。

原文地址:http://www.cnblogs.com/wwjjll/p/16886559.html

1. 本站所有资源来源于用户上传和网络,如有侵权请邮件联系站长! 2. 分享目的仅供大家学习和交流,请务用于商业用途! 3. 如果你也有好源码或者教程,可以到用户中心发布,分享有积分奖励和额外收入! 4. 本站提供的源码、模板、插件等等其他资源,都不包含技术服务请大家谅解! 5. 如有链接无法下载、失效或广告,请联系管理员处理! 6. 本站资源售价只是赞助,收取费用仅维持本站的日常运营所需! 7. 如遇到加密压缩包,默认解压密码为"gltf",如遇到无法解压的请联系管理员! 8. 因为资源和程序源码均为可复制品,所以不支持任何理由的退款兑现,请斟酌后支付下载 声明:如果标题没有注明"已测试"或者"测试可用"等字样的资源源码均未经过站长测试.特别注意没有标注的源码不保证任何可用性