python面...

python面试笔试精选

2016-09-03  本文已影响1374人  这个手刹丶不太灵
import datetime
import functools
def log(func):
    @functools.wraps(func)
    def wrapper(*args,**kw):
        d1 = datetime.datetime.now()
        back = func(*args,**kw)
        print('excute in %s' % str(datetime.datetime.now() -d1))
        return back
    return wrapper

webbrowser模块提供了一个高级接口来显示基于Web的文档,大部分情况下只需要简单的调用open()方法。webbrowser定义了如下的异常:exception webbrowser.Error, 当浏览器控件发生错误是会抛出这个异常 webbrowser有以下方法:
webbrowser.open(url[, new=0[, autoraise=1]])
这个方法是在默认的浏览器中显示url, 如果new = 0, 那么url会在同一个浏览器窗口下打开,如果new = 1, 会打开一个新的窗口,如果new = 2, 会打开一个新的tab, 如果autoraise = true, 窗口会自动增长。
webbrowser.open_new(url)
在默认浏览器中打开一个新的窗口来显示url, 否则,在仅有的浏览器窗口中打开url
webbrowser.open_new_tab(url)
在默认浏览器中当开一个新的tab来显示url, 否则跟open_new()一样
webbrowser.get([name]) 根据name返回一个浏览器对象,如果name为空,则返回默认的浏览器
webbrowser.register(name, construtor[, instance])
注册一个名字为name的浏览器,如果这个浏览器类型被注册就可以用get()方法来获取。

class Singleton(object):
    def __new__(cls):
    # 关键在于这,每一次实例化的时候,我们都只会返回这同一个instance对象
    if not hasattr(cls, 'instance'):
        cls.instance = super(Singleton, cls).__new__(cls)
    return cls.instance

obj1 = Singleton()
obj2 = Singleton()
obj1.attr1 = 'value1'
print obj1.attr1, obj2.attr1
print obj1 is obj2
class Borg(object):
    _state = {}
    def __new__(cls, *args, **kw):
        ob = super(Borg, cls).__new__(cls, *args, **kw)
        ob.__dict__ = cls._state
        return ob   

class MyClass2(Borg):
        a = 1

one = MyClass2()   
two = MyClass2()
#one和two是两个不同的对象
#但是one和two具有相同的(同一个__dict__属性),见:    
print id(one.__dict__)   
#30104000    
print id(two.__dict__)   
#30104000    
import functools
def singleton(cls):
    instances = {}
    @functool.wraps(cls)
    def getinstance(*args, **kw):
        if cls not in instances:
            instances[cls] = cls(*args, **kw)
        return instances[cls]
    return getinstance  

@singleton
class MyClass:
# mysingleton.py
class My_Singleton(object):
    def foo(self):
        pass        
my_singleton = My_Singleton()
# to use
from mysingleton import my_singleton
my_singleton.foo()
    from email.mime.text import MIMEText
msg = MIMEText('hello, send by Python...', 'plain', 'utf-8')
        # 输入Email地址和口令:
from_addr = input('From: ')
password = input('Password: ')
# 输入收件人地址:
to_addr = input('To: ')
# 输入SMTP服务器地址:
smtp_server = input('SMTP server: ')
import smtplib
server = smtplib.SMTP(smtp_server, 25) # SMTP协议默认端口是25
server.set_debuglevel(1)
server.login(from_addr, password)
server.sendmail(from_addr, [to_addr], msg.as_string())
server.quit()
        ```
* ###python文件操作?
    * `os.remove(filename)  `
    * `shutil.copyfile('a.py','')`
* ###写一个简单的socket编程
    * 客户端
    ```python
import socket
#创建socket对象
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
#建立连接
s = connect(('www.sina.com',80))
#发送数据
s.send(b'GET / HTTP/1.1\r\nHost: www.sina.com.cn\r\nConnection: close\r\n\r\n')
#接受数据
buffer = []
while True:
          d = s.recv(1024)
          if d:
              buffer.append(d)
          else:
              break
data = b''.join(buffer)
s.close()
* 服务端
    s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
    #监听端口
    s.bind(('127.0.0.1',9999))
    #调用listen()方法开始监听端口,传入的参数指定等待连接的最大数量
    s.listen(5)
    while True:
          #接受一个新连接
          sock,addr = s.accept()
          #创建新线程处理TCP连接
          t = threading.Thread(target=tcplink,args=(sock,addr))
          t.start()
    ```
```python
def tcplink(sock,addr):
          sock.send(b'welcome')
          while True:
              data = sock.recv(1024)
              time.sleep(1)
              if not data or data.decode('utf-8') == 'exit':
                  break
              sock.send('hello %s ' % data.decode('utf-8').encode('utf-8'))
          sock.close()
from django.conf import settings  
    from django.core.cache import cache  
    #read cache user id  
    def read_from_cache(self, user_name):  
          key = 'user_id_of_'+user_name  
          value = cache.get(key)  
          if value == None:  
              data = None  
          else:  
              data = json.loads(value)  
          return data  
    #write cache user id  
    def write_to_cache(self, user_name):  
          key = 'user_id_of_'+user_name  
          cache.set(key, json.dumps(user_name), settings.NEVER_REDIS_TIMEOUT) 
  class Stack(object):
      def __init__(self):
          self.stack=[]
      def isEmpty(self):
          return self.stack==[]
      def push(self,item):
          self.stack.append(item)
      def pop(self):
          if self.isEmpty():
              raise IndexError,'pop from empty stack'
          return self.stack.pop()
      def peek(self):
          return self.stack[-1]
      def size(self):
          return len(self.stack)
horses = [1, 2, 3, 4]
>>> races = itertools.permutations(horses)
>>> print(races)
<itertools.permutations object at 0xb754f1dc>
>>> print(list(itertools.permutations(horses)))
[(1, 2, 3, 4), (1, 2, 4, 3), (1, 3, 2, 4), (1, 3, 4, 2),(1, 4, 2, 3), (1, 4, 3, 2), (2, 1, 3, 4), (2, 1, 4, 3), (2, 3, 1, 4), (2, 3, 4, 1), (2, 4, 1, 3), (2, 4, 3, 1), (3, 1, 2, 4), (3, 1, 4, 2), (3, 2, 1, 4), (3, 2, 4, 1), (3, 4, 1, 2), (3, 4, 2, 1), (4, 1, 2, 3), (4, 1, 3, 2), (4, 2, 1, 3), (4, 2, 3, 1), (4, 3, 1, 2), (4, 3, 2, 1)]
上一篇下一篇

猜你喜欢

热点阅读