1.python什么是聊天弱引用,__weakref__如何使用?
2.Pythonè¦åªäºè¦ç¹è¦å¦ä¹
3.å¦ä½ç¨Pythonç¼åä¸ä¸ªè天室
python什么是弱引用,__weakref__如何使用?
大家好,我是室源程序员老王。让我们来谈谈Python中的源聊弱引用。
假设我们需要创建一个匿名聊天室。天程为了实现这一目标,聊天我们首先定义了一个代表用户的室源javaweb招聘网源码类User。由于匿名聊天,源聊用户无需注册,天程为每个用户分配一个唯一的聊天id。我们确保id的室源独特性,通过维护一个全局字典,源聊存储当前所有id与用户之间的天程关系,一旦发生冲突,聊天重新生成id并更新全局字典。室源
随后,源聊我们定义了聊天室函数chat_room,该函数允许多人参与聊天。在聊天结束后,这些匿名用户将失去作用。然而,问题在于,vb地图源码当用户被创建时,全局字典id_user中将记录所有User实例的引用。即使chat_room返回,id_user仍保有所有User的引用,导致这些实例无法被垃圾回收,进而影响id的重用。
解决这个问题的一种方法是,在chat_room返回前从id_user中删除用户引用。但考虑到实际聊天室功能的复杂性以及可能的异常处理,选择正确的c wifi 源码del id_user的位置需要谨慎。此外,这种操作在逻辑上并不连贯,易于引入错误。
引入弱引用提供了一种替代解决方案。Python的weakref库中的WeakValueDictionary可以作为替代id_user的普通字典。这个WeakValueDictionary实现了字典接口,但其特殊之处在于,它的值为弱引用。
强引用,如chat_room中的游戏挂机源码u1和u2,只要对象还存在强引用,它们将不会被垃圾回收。因此,u1和u2指向的User实例在chat_room中不会被回收。然而,弱引用不同,如id_user中的值。虽然它们同样指向User实例,但只要实例没有其他强引用,这些User将被回收,呼吸灯源码并且id_user中对应的条目也会被删除。因此,当chat_room返回时,u1和u2指向的User已无强引用,id_user会自动执行删除操作,无需显式调用del。
输出结果显示,尽管我们没有删除id_user中的元素,id_user仍然为空,符合预期。如果全局变量中已有一个User,再次运行程序,id_user将保留一个User,因为全局变量u一直引用着这个User。
除了WeakValueDictionary,还有WeakKeyDictionary和WeakSet。WeakKeyDictionary中Key为弱引用,而WeakSet相当于只有Key没有Value的WeakKeyDictionary。更多细节在这里就不赘述。
ref类允许我们创建一个简单的弱引用。例如,我们可以对全局的User u创建一个ref类的实例。当我们调用u_ref()时,ref类会返回u对应的强引用。如果在调用u_ref()之前,User的强引用已经消失,再次调用u_ref()将返回None。
最后要指出,并非所有对象都支持弱引用。例如,数字和字符串不支持弱引用。考虑到这些类型在计算中可能重复出现,将其弱引用可能不符合逻辑。相比之下,类的实例、容器等对象更适合使用弱引用。完整的可弱引用的对象列表在文档中提供,但在实际使用中,无需特意查阅。
Pythonè¦åªäºè¦ç¹è¦å¦ä¹
é¶æ®µä¸ï¼Pythonå¼ååºç¡
Pythonå ¨æ å¼åä¸äººå·¥æºè½ä¹Pythonå¼ååºç¡ç¥è¯å¦ä¹ å 容å æ¬ï¼Pythonåºç¡è¯æ³ãæ°æ®ç±»åãå符ç¼ç ãæ件æä½ãå½æ°ãè£ é¥°å¨ãè¿ä»£å¨ãå ç½®æ¹æ³ã常ç¨æ¨¡åçã
é¶æ®µäºï¼Pythoné«çº§ç¼ç¨åæ°æ®åºå¼å
Pythonå ¨æ å¼åä¸äººå·¥æºè½ä¹Pythoné«çº§ç¼ç¨åæ°æ®åºå¼åç¥è¯å¦ä¹ å 容å æ¬ï¼é¢å对象å¼åãSocketç½ç»ç¼ç¨ã线ç¨ãè¿ç¨ãéåãIOå¤è·¯æ¨¡åãMysqlæ°æ®åºå¼åçã
é¶æ®µä¸ï¼å端å¼å
Pythonå ¨æ å¼åä¸äººå·¥æºè½ä¹å端å¼åç¥è¯å¦ä¹ å 容å æ¬ï¼HtmlãCSSãJavaScriptå¼åãJquery&bootstrapå¼åãå端æ¡æ¶VUEå¼åçã
é¶æ®µåï¼WEBæ¡æ¶å¼å
Pythonå ¨æ å¼åä¸äººå·¥æºè½ä¹WEBæ¡æ¶å¼åå¦ä¹ å 容å æ¬ï¼Djangoæ¡æ¶åºç¡ãDjangoæ¡æ¶è¿é¶ãBBS+Blogå®æ项ç®å¼åãç¼ååéåä¸é´ä»¶ãFlaskæ¡æ¶å¦ä¹ ãTornadoæ¡æ¶å¦ä¹ ãRestful APIçã
é¶æ®µäºï¼ç¬è«å¼å
Pythonå ¨æ å¼åä¸äººå·¥æºè½ä¹ç¬è«å¼åå¦ä¹ å 容å æ¬ï¼ç¬è«å¼åå®æã
é¶æ®µå ï¼å ¨æ 项ç®å®æ
Pythonå ¨æ å¼åä¸äººå·¥æºè½ä¹å ¨æ 项ç®å®æå¦ä¹ å 容å æ¬ï¼ä¼ä¸åºç¨å·¥å ·å¦ä¹ ãCRM客æ·å ³ç³»ç®¡çç³»ç»å¼åãè·¯é£å¦åå¨çº¿æè²å¹³å°å¼åçã
é¶æ®µä¸ï¼ç®æ³&设计模å¼
é¶æ®µå «ï¼æ°æ®åæ
Pythonå ¨æ å¼åä¸äººå·¥æºè½ä¹æ°æ®åæå¦ä¹ å 容å æ¬ï¼éèéååæã
é¶æ®µä¹ï¼æºå¨å¦ä¹ ãå¾åè¯å«ãNLPèªç¶è¯è¨å¤ç
Pythonå ¨æ å¼åä¸äººå·¥æºè½ä¹äººå·¥æºè½å¦ä¹ å 容å æ¬ï¼æºå¨å¦ä¹ ãå¾å½¢è¯å«ã人工æºè½ç©å ·å¼åçã
é¶æ®µåï¼Linuxç³»ç»&ç¾ä¸çº§å¹¶åæ¶æ解å³æ¹æ¡
é¶æ®µåä¸ï¼é«å¹¶åè¯è¨GOå¼å
Pythonå ¨æ å¼åä¸äººå·¥æºè½ä¹é«å¹¶åè¯è¨GOå¼åå¦ä¹ å 容å æ¬ï¼GOè¯è¨åºç¡ãæ°æ®ç±»åä¸æ件IOæä½ãå½æ°åé¢å对象ã并åç¼ç¨çã
å¦ä½ç¨Pythonç¼åä¸ä¸ªè天室
ä¸ã课ç¨ä»ç»1.ç®ä»
æ¬æ¬¡é¡¹ç®è¯¾æ¯å®ç°ç®åè天室ç¨åºçæå¡å¨ç«¯å客æ·ç«¯ã
2.ç¥è¯ç¹
æå¡å¨ç«¯æ¶åå°asyncoreãasynchatåsocketè¿å 个模åï¼å®¢æ·ç«¯ç¨å°äºtelnetlibãwxãtimeåthreadè¿å 个模åã
3.æéç¯å¢
æ¬æ¬¡è¯¾ä¸ç¼å客æ·ç«¯éè¦ç¨å°wxPythonï¼å®æ¯ä¸ä¸ªGUIå·¥å ·å ï¼è¯·å 使ç¨ä¸é¢çå½ä»¤å®è£ ï¼
$ sudo apt-get install python-wxtools
å¯ç 为shiyanlou
4.项ç®æææªå¾
ç»å½çªå£
è天çªå£
äºã项ç®å®æï¼æå¡å¨ç«¯ï¼
1.æå¡å¨ç±»
é¦å éè¦ä¸ä¸ªè天æå¡å¨ï¼è¿é继æ¿asyncoreçdispatcherç±»æ¥å®ç°ï¼ä»£ç å¦ä¸
class ChatServer(dispatcher):
"""
è天æå¡å¨
"""
def __init__(self, port):
dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.set_reuse_addr()
self.bind(('', port))
self.listen(5)
self.users = { }
self.main_room = ChatRoom(self)
def handle_accept(self):
conn, addr = self.accept()
ChatSession(self, conn)
2.ä¼è¯ç±»
æäºæå¡å¨ç±»è¿éè¦è½ç»´æ¤æ¯ä¸ªç¨æ·çè¿æ¥ä¼è¯ï¼è¿é继æ¿asynchatçasync_chatç±»æ¥å®ç°ï¼ä»£ç å¦ä¸ï¼
class ChatSession(async_chat):
"""
è´è´£ååç¨æ·éä¿¡
"""
def __init__(self, server, sock):
async_chat.__init__(self, sock)
self.server = server
self.set_terminator('\n')
self.data = []
self.name = None
self.enter(LoginRoom(server))
def enter(self, room):
'ä»å½åæ¿é´ç§»é¤èªèº«ï¼ç¶åæ·»å å°æå®æ¿é´'
try:
cur = self.room
except AttributeError:
pass
else:
cur.remove(self)
self.room = room
room.add(self)
def collect_incoming_data(self, data):
'æ¥å客æ·ç«¯çæ°æ®'
self.data.append(data)
def found_terminator(self):
'å½å®¢æ·ç«¯çä¸æ¡æ°æ®ç»ææ¶çå¤ç'
line = ''.join(self.data)
self.data = []
try:
self.room.handle(self, line)
except EndSession:
self.handle_close()
def handle_close(self):
async_chat.handle_close(self)
self.enter(LogoutRoom(self.server))
3.å½ä»¤è§£éå¨
ç°å¨å°±éè¦ä¸ä¸ªå½ä»¤è§£éå¨è½å¤è§£éç¨æ·çå½ä»¤ï¼ä¾å¦ç»å½ãæ¥è¯¢å¨çº¿ç¨æ·ååæ¶æ¯çï¼ä»£ç å¦ä¸ï¼
class CommandHandler:
"""
å½ä»¤å¤çç±»
"""
def unknown(self, session, cmd):
'ååºæªç¥å½ä»¤'
session.push('Unknown command: %s\n' % cmd)
def handle(self, session, line):
'å½ä»¤å¤ç'
if not line.strip():
return
parts = line.split(' ', 1)
cmd = parts[0]
try:
line = parts[1].strip()
except IndexError:
line = ''
meth = getattr(self, 'do_' + cmd, None)
try:
meth(session, line)
except TypeError:
self.unknown(session, cmd)
4.æ¿é´
æ¥ä¸æ¥å°±éè¦å®ç°è天室çæ¿é´äºï¼è¿éæ们å®ä¹äºä¸ç§æ¿é´ï¼åå«æ¯ç¨æ·åç»å½æ¶çæ¿é´ãè天çæ¿é´åéåºç»å½çæ¿é´ï¼è¿ä¸ç§æ¿é´é½æä¸ä¸ªå ¬å ±çç¶ç±»ï¼ä»£ç å¦ä¸ï¼
class Room(CommandHandler):
"""
å å«å¤ä¸ªç¨æ·çç¯å¢ï¼è´è´£åºæ¬çå½ä»¤å¤çå广æ
"""
def __init__(self, server):
self.server = server
self.sessions = []
def add(self, session):
'ä¸ä¸ªç¨æ·è¿å ¥æ¿é´'
self.sessions.append(session)
def remove(self, session):
'ä¸ä¸ªç¨æ·ç¦»å¼æ¿é´'
self.sessions.remove(session)
def broadcast(self, line):
'åææçç¨æ·åéæå®æ¶æ¯'
for session in self.sessions:
session.push(line)
def do_logout(self, session, line):
'éåºæ¿é´'
raise EndSession
class LoginRoom(Room):
"""
åç»å½çç¨æ·çæ¿é´
"""
def add(self, session):
'ç¨æ·è¿æ¥æåçååº'
Room.add(self, session)
session.push('Connect Success')
def do_login(self, session, line):
'ç»å½å½ä»¤å¤ç'
name = line.strip()
if not name:
session.push('UserName Empty')
elif name in self.server.users:
session.push('UserName Exist')
else:
session.name = name
session.enter(self.server.main_room)
class ChatRoom(Room):
"""
è天ç¨çæ¿é´
"""
def add(self, session):
'广ææ°ç¨æ·è¿å ¥'
session.push('Login Success')
self.broadcast(session.name + ' has entered the room.\n')
self.server.users[session.name] = session
Room.add(self, session)
def remove(self, session):
'广æç¨æ·ç¦»å¼'
Room.remove(self, session)
self.broadcast(session.name + ' has left the room.\n')
def do_say(self, session, line):
'客æ·ç«¯åéæ¶æ¯'
self.broadcast(session.name + ': ' + line + '\n')
def do_look(self, session, line):
'æ¥çå¨çº¿ç¨æ·'
session.push('Online Users:\n')
for other in self.sessions:
session.push(other.name + '\n')
class LogoutRoom(Room):
"""
ç¨æ·éåºæ¶çæ¿é´
"""
def add(self, session):
'ä»æå¡å¨ä¸ç§»é¤'
try:
del self.server.users[session.name]
except KeyError:
pass
5.æå¡å¨ç«¯å®æ´ä»£ç
#!/usr/bin/python
# encoding: utf-8
from asyncore import dispatcher
from asynchat import async_chat
import socket, asyncore
PORT = #端å£
class EndSession(Exception):
"""
èªå®ä¹ä¼è¯ç»ææ¶çå¼å¸¸
"""
pass
class CommandHandler:
"""
å½ä»¤å¤çç±»
"""
def unknown(self, session, cmd):
'ååºæªç¥å½ä»¤'
session.push('Unknown command: %s\n' % cmd)
def handle(self, session, line):
'å½ä»¤å¤ç'
if not line.strip():
return
parts = line.split(' ', 1)
cmd = parts[0]
try:
line = parts[1].strip()
except IndexError:
line = ''
meth = getattr(self, 'do_' + cmd, None)
try:
meth(session, line)
except TypeError:
self.unknown(session, cmd)
class Room(CommandHandler):
"""
å å«å¤ä¸ªç¨æ·çç¯å¢ï¼è´è´£åºæ¬çå½ä»¤å¤çå广æ
"""
def __init__(self, server):
self.server = server
self.sessions = []
def add(self, session):
'ä¸ä¸ªç¨æ·è¿å ¥æ¿é´'
self.sessions.append(session)
def remove(self, session):
'ä¸ä¸ªç¨æ·ç¦»å¼æ¿é´'
self.sessions.remove(session)
def broadcast(self, line):
'åææçç¨æ·åéæå®æ¶æ¯'
for session in self.sessions:
session.push(line)
def do_logout(self, session, line):
'éåºæ¿é´'
raise EndSession
class LoginRoom(Room):
"""
åç»å½çç¨æ·çæ¿é´
"""
def add(self, session):
'ç¨æ·è¿æ¥æåçååº'
Room.add(self, session)
session.push('Connect Success')
def do_login(self, session, line):
'ç»å½å½ä»¤å¤ç'
name = line.strip()
if not name:
session.push('UserName Empty')
elif name in self.server.users:
session.push('UserName Exist')
else:
session.name = name
session.enter(self.server.main_room)
class ChatRoom(Room):
"""
è天ç¨çæ¿é´
"""
def add(self, session):
'广ææ°ç¨æ·è¿å ¥'
session.push('Login Success')
self.broadcast(session.name + ' has entered the room.\n')
self.server.users[session.name] = session
Room.add(self, session)
def remove(self, session):
'广æç¨æ·ç¦»å¼'
Room.remove(self, session)
self.broadcast(session.name + ' has left the room.\n')
def do_say(self, session, line):
'客æ·ç«¯åéæ¶æ¯'
self.broadcast(session.name + ': ' + line + '\n')
def do_look(self, session, line):
'æ¥çå¨çº¿ç¨æ·'
session.push('Online Users:\n')
for other in self.sessions:
session.push(other.name + '\n')
class LogoutRoom(Room):
"""
ç¨æ·éåºæ¶çæ¿é´
"""
def add(self, session):
'ä»æå¡å¨ä¸ç§»é¤'
try:
del self.server.users[session.name]
except KeyError:
pass
class ChatSession(async_chat):
"""
è´è´£ååç¨æ·éä¿¡
"""
def __init__(self, server, sock):
async_chat.__init__(self, sock)
self.server = server
self.set_terminator('\n')
self.data = []
self.name = None
self.enter(LoginRoom(server))
def enter(self, room):
'ä»å½åæ¿é´ç§»é¤èªèº«ï¼ç¶åæ·»å å°æå®æ¿é´'
try:
cur = self.room
except AttributeError:
pass
else:
cur.remove(self)
self.room = room
room.add(self)
def collect_incoming_data(self, data):
'æ¥å客æ·ç«¯çæ°æ®'
self.data.append(data)
def found_terminator(self):
'å½å®¢æ·ç«¯çä¸æ¡æ°æ®ç»ææ¶çå¤ç'
line = ''.join(self.data)
self.data = []
try:
self.room.handle(self, line)
except EndSession:
self.handle_close()
def handle_close(self):
async_chat.handle_close(self)
self.enter(LogoutRoom(self.server))
class ChatServer(dispatcher):
"""
è天æå¡å¨
"""
def __init__(self, port):
dispatcher.__init__(self)
self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
self.set_reuse_addr()
self.bind(('', port))
self.listen(5)
self.users = { }
self.main_room = ChatRoom(self)
def handle_accept(self):
conn, addr = self.accept()
ChatSession(self, conn)
if __name__ == '__main__':
s = ChatServer(PORT)
try:
asyncore.loop()
except KeyboardInterrupt:
ä¸ã项ç®å®æï¼å®¢æ·ç«¯ï¼
å®æäºæå¡å¨ç«¯åï¼å°±éè¦å®ç°å®¢æ·ç«¯äºï¼è¿é客æ·ç«¯è¿æ¥æå¡å¨ä½¿ç¨äºtelnetlib模åã
1.ç»å½çªå£
è¿éçå¾å½¢çé¢å éæ©äºwxPythonï¼åé¢æå®è£ 说æï¼ç»å½çªå£éè¿ç»§æ¿wx.Frameç±»æ¥å®ç°ï¼ä»£ç å¦ä¸ï¼
class LoginFrame(wx.Frame):
"""
ç»å½çªå£