1.写一个类,有个name属性,如果name赋值为非字符串,就不让放
class Name(object):
def __init__(self, name):
self.name = name
def __setattr__(self, key, name):
if isinstance(name, str):
self.__dict__[key] = name
else:
print('Name Error:不是字符串,无效')
def __getattr__(self, item):
return self[item]
user = Name(name='xxq')
user.name = 123123
print('用户名为:', user.name)
老师的方法:
# 自定义异常
class NotStrException(BaseException):
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class Person():
def __setattr__(self, key, value):
if isinstance(value, str): # isinstance issubclass
# setattr(self,key,value) #内部是这么执行的self.key=value
# self.__dict__[key]=value
object.__setattr__(self, key, value)
else:
# print("你不能放")
raise NotStrException('不是字符串异常')
person = Person()
try:
# person.name=99
person.name = 'xxq'
except NotStrException as e:
print(e)
print(person.name)
2.通过上下文管理器写一个mysql的连接,通过with管理
import pymysql
class Mysql:
def __enter__(self):
self.conn = pymysql.connect(host='127.0.0.1',
user='root',
password="123456",
database='0701test',
port=3306)
self.cursor = self.conn.cursor(cursor=pymysql.cursors.DictCursor) # 查出来数据是字典格式
return self.cursor
def __exit__(self, exc_type, exc_val, exc_tb):
self.cursor.close()
with Mysql() as db:
sql = 'select * from info'
db.execute(sql)
result = db.fetchall()
for i in result:
print(i)
老师的代码:
import pymysql
class Mysql():
def __enter__(self):
self.conn = pymysql.connect(host='127.0.0.1', user='root', password="123456",
database='mytest', port=3306)
return self.conn # 会被as 后的对象拿到
def __exit__(self, exc_type, exc_val, exc_tb):
self.conn.close()
with Mysql() as mysql:
mysql.cursor()
3.使用django实现token功能
待发布...