深入python的类和对象
1、为类或对象动态创建属性或方法
2、__slots__ = ('name','age'),【实例】只能创建指定的属性属性或方法 ---新式类
3、执行父类的构造函数的不同 Father.__init__(self) --经典类 super(Son,self).__init__() --新式类 4、Person.__bases__ 只会显示一层继承的所有父类 5、__call__ __call__ 一个已经实例化的对象p,在调用p() 6、python中一切都是对象,类本身也是对象,类是由type产生的。
class Foo pass Bar = type('Bar',(object,),{'name':123,'Func':Hello}) 既然这样,那么对于定义的类来说,只要定义了一个类,就调用一次 type类的构造函数,如何验证?
7、__metaclass__ 可以指定类是由那个type来产生的
1 2 3 4 5 6 7 8 9 | class MetaClass( type ):
def __init__( self ,name,bases,dicts):
print name
class C1:
__metaclass__ = MetaClass
class C2:
__metaclass__ = MetaClass
|
8、__init__ __new__ __call__ 我们知道执行 f = Foo() 会默认执行构造函数 __init__ 实际上执行了:type('Foo',bases,dicts).__call__('Foo')
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | class MetaClass( type ):
def __init__( self ,name,bases,dicts):
print name
def __call__( self , * args, * * kwargs):
print self
result = self .__new__( self , * args, * * kwargs)
print result
type (result).__init__(result, * args, * * kwargs)
return result
class C1:
__metaclass__ = MetaClass
def __init__( self ):
print 'c1.__init__'
self .name = 'alex'
def __new__( cls , * args, * * kwargs):
print cls
print args
print kwargs
return object .__new__( cls , * args, * * kwargs)
def Hello( self ):
print 'hello'
class C2:
__metaclass__ = MetaClass
#c = C1()
c1 = object .__new__(C1)
c1.Hello()
|
Session
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | #!/usr/bin/env python
#coding:utf-8
from hashlib import sha1
import os, time
create_session_id = lambda : sha1( '%s%s' % (os.urandom( 16 ), time.time())).hexdigest()
class session( object ):
'''自定义session框架'''
_sessionid = '__sessionid'
def __init__( self ,request,timeout = 1800 ):
#根据request从cookie中获取 __sessionid 的值
self ._request = request
self ._timeout = 1800
self ._redis = {}
self .__initialize()
def __initialize( self ):
id = self ._request.get_cookie(session._sessionid)
if not id :
id = create_session_id()
self ._request.set_cookie(session._sessionid, id )
self ._id = id
print id
def __getitem__( self ,name):
#return self._redis.hget(self._id, name)
print name
return name
def __setitem__( self ,name,value):
#self._redis.hset(self._id, name, value)
#self._redis.expire(self._id, self.session_lifetime)
print name,value
def __delitem__( self , name):
#return self._redis.hdel(self._id, name)
return 'del'
__all__ = [ "session" ]
|
Tornado
View Code
1、根据请求不同定位到指定类的 get、post、put、delete方法上
https://chrome.google.com/webstore/detail/postman-rest-client/fdmmgilgnpjigdojojpjoooidkmcomcm
2、render
|