python 类demo(2)__metaclass__批量化添加属性

来源:互联网 发布:上海淘宝客服招聘 编辑:程序博客网 时间:2024/06/05 11:36

__metaclass__批量化添加属性


>>> def ma(cls):#注意cls  不然报错。没有ma属性print 'method a'>>> def mb(cls):#注意cls  不然报错。没有mb属性print 'method b'>>> method_dict = {'ma':ma,'mb':mb}>>> class Dy(type):def __new__(cls,name, bases, dct):if name[:3] == 'Abc':dct.update(method_dict)return type.__new__(cls, name, bases, dct)def __init__(cls, name, bases, dct):super(Dy,cls).__init__(name,bases,dct)>>> class AbcTest(object):__metaclass__ = Dydef mc(self,x):print x *3>>> class NotAbc(object):__metaclass__ = Dydef md(self,x):print x * 3>>> def main():a = AbcTest()a.mc(3)       #实例 a 调用 AbcTest 的 mc()  #9a.ma() #因为DY类中增加了 ma,mb 属性,所以可以调用 ma,mb 函数  #method aprint dir(a)    #返回实例 a 拥有的属性b = NotAbc()   print dir(b)#实例 b 没有增加 ma,mb 属性>>> main()9method a['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__','__metaclass__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'ma', 'mb', 'mc']['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__','__metaclass__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'md']


通过__metaclass__ = 调用类 动态的给类 AbcTest() 添加属性,(判断类的名称)


#!/usr/bin/python  #coding :utf-8  from types import FunctionType   def login_required(func):      print 'login check logic here'     return func    class LoginDecorator(type):      def __new__(cls, name, bases, dct):          for name, value in dct.iteritems():              if name notin ('__metaclass__','__init__', '__module__')and\                  type(value) == FunctionType:                  value = login_required(value)               dct[name] = value          return type.__new__(cls, name, bases, dct)    class Operation(object):      __metaclass__ = LoginDecorator       def delete(self, x):          print 'deleted %s' % str(x)    def main():      op = Operation()      op.delete('test')   if __name__ == '__main__':      main() 

2. 批量的对某些方法使用decorator,而不需要每次都在方法的上面加入@decorator_func 这个其实有应用场景的,就是比如我们cgi程序里面,很多需要验证登录或者是否有权限的,只有验证通过之后才 可以操作。那么如果你有很多个操作都需要这样做,我们一般情况下可以手动在每个方法的前头用@login_required 类似这样的方式。那如果学习了metaclass的使用的话,这次你也可以这样做:  这样子你就可以不用在delete函数上面写@login_required, 也能达到decorat的效果了。不过可读性就差点了。

原创粉丝点击