(1)用encode("utf8")把unicode编码变成str/(2)python中@property,@x.setter和@x.deleter/(3)MD5加密编码

(1)用encode(“utf8”)把unicode编码变成str,

   if isinstance(s, unicode):
        s = s.encode("utf8")

(2)python中@property,@x.setter和@x.deleter

@property可以将python定义的函数“当做”属性访问,从而提供更加友好访问方式,但是有时候setter/deleter也是需要的。
1》只有@property表示只读。
2》同时有@property和@x.setter表示可读可写。

3》同时有@property和@x.setter和@x.deleter表示可读可写可删除。
class student(object):  #新式类
    def __init__(self,id):
        self.__id=id
    @property  #读
    def score(self):
        return self._score
    @score.setter #写
    def score(self,value):
        if not isinstance(value,int):
            raise ValueError('score must be an integer!')
        if value<0 or value>100:
            raise ValueError('score must between 0 and 100')
        self._score=value
    @property #读(只能读,不能写)
    def get_id(self):
        return self.__id

s=student('123456')
a=s.score #没有设置,就读取,AttributeError: 'student' object has no attribute '_score'
s.score=60 #写
print s.score #读
#s.score=-2 #ValueError: score must between 0 and 100
#s.score=32.6 #ValueError: score must be an integer!
s.score=100 #写
print s.score #读
print s.get_id #读(只能读,不可写)
#s.get_id=456 #只能读,不可写:AttributeError: can't set attribute

(3)MD5加密编码

import hashlib
def gen_md5_eid(s):
    """
    s 公司名字 utf8编码
    """
    if not s:
        raise Exception("s cannot be void")

    m = hashlib.md5()
    if isinstance(s, unicode):
        s = s.encode("utf8")
    m.update(s)
    return m.hexdigest().upper()
# a = gen_md5_eid('哈哈哈')
a = gen_md5_eid(u'哈哈哈')
print(a)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值