(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)