temp

首先来看看上述三个魔法方法的定义吧:

(1)__getattr__(self, item):

在访问对象的item属性的时候,如果对象并没有这个相应的属性,方法,那么将会调用这个方法来处理。。。这里要注意的时,假如一个对象叫fjs, 他有一个属性:fjs.name = "fjs",那么在访问fjs.name的时候因为当前对象有这个属性,那么将不会调用__getattr__()方法,而是直接返回了拥有的name属性了

(2)__setattr__(self, item, value):

当试图对象的item特性赋值的时候将会被调用。。

(3)__getattribute__(self, item):

这个只有在新式类中才有的,对于对象的所有特性的访问,都将会调用这个方法来处理。。。可以理解为在__getattr__之前

嗯。。。有了这几个方法就可以干很多很多的事情了。。。例如拦截器啥的。。。动态代理啥的。。。很方便就能实现了。。。起码比用java实现类似的功能方便多啦。。。。

不过需要注意的时候,在重写这些方法的时候需要特别的小心,因为容易引起循环调用。。。。

这里先来举一个例子,用于实现拦截所有的特性访问,在访问的时候打log啥的:[python] view plain copy

  1. # -*- coding: utf-8 -*-
  2. class Fjs(object):
  3. def __init__(self, name):
  4. self.name = name
    1. def hello(self):
  5. print "said by : ", self.name
    1. def __getattribute__(self, item):
  6. print "访问了特性:" + item
  7. return object.__getattribute__(self, item)
      1. fjs = Fjs("fjs")
  8. print fjs.name
  9. fjs.hello()

上述代码的输出如下:[python] view plain copy

  1. 访问了特性:name
  2. fjs
  3. 访问了特性:hello
  4. said by : 访问了特性:name
  5. fjs

很简单就实现了拦截的功能吧。。。而且这里可以知道__getattribute__方法拦截了属性和方法的访问。。这里也就是所谓的所有的特性的访问了。。不过要注意的是:__getattribute__只有在新式类中才能用的。。。

嗯。。接下来配合使用__getattr__和__getattribute__来实现一个非切入式的编程:[python] view plain copy

  1. # -*- coding: utf-8 -*-
  2. class Fjs(object):
  3. def __init__(self, name):
  4. self.name = name
    1. def hello(self):
  5. print "said by : ", self.name
    1. def fjs(self, name):
  6. if name == self.name:
  7. print "yes"
  8. else:
  9. print "no"
    1. class Wrap_Fjs(object):
  10. def __init__(self, fjs):
  11. self._fjs = fjs
    1. def __getattr__(self, item):
  12. if item == "hello":
  13. print "调用hello方法了"
  14. elif item == "fjs":
  15. print "调用fjs方法了"
  16. return getattr(self._fjs, item)
    1. fjs = Wrap_Fjs(Fjs("fjs"))
  17. fjs.hello()
  18. fjs.fjs("fjs")

这里通过__getattr__方法,将所有的特性的访问都路由给了内部的fjs对象。。。。。。

最后,关于__setattr__()方法,这个就不细说了。。。不过他的使用还需要特别注意一些。。因为稍不注意就容易陷入循环调用了。。。。

results matching ""

    No results matching ""