在Python中动态绑定property
在Python中可以把property动态的绑定的object的继承类中,并且可以定义带有参数的get和set方法。
比如,我们定义了全局变量g,然后通过两个方法来存取g的内容
def get_g(self):
return g
def set_g(self, _g):
global g
g = _g
定义一个object的继承类A:
class A(object):
pass
然后可以通过setattr把一个property动态的bind到A中:
setattr(A, 'g', property(get_g, set_g))
我们我们可能还要对动态bind做一些定制,比如我们可能有两个全局变量,g1和g2,希望在绑定时动态的决定到底是绑谁,那么我们就可以这么做:
def get_pp(name):
def get_g(self):
return globals()[name]
def set_g(self, _g):
globals()[name] = _g
return property(get_g, set_g)
然后可以setattr(A, 'g', get_pp('g1') ),从而把g1关联到的A的‘g’属性。
相关文档:
You are here: Home ‣ Dive Into Python 3 ‣
Difficulty level: ♦♢♢♢♢
Installing Python 安装Python
❝ Tempora mutantur nos et mutamur in illis. (Times change, and we change with them.) ❞
— ancient Roman proverb
D ......
知识点
1.线程是“轻量级”进程,因为相较于进程的创建和管理,操作系统通常会用较少的资源来创建和管理线程。操作系统要为新建的进程分配单独的内在空间和数据;相反,程序中的线程在相同的内存空间中执行,并共享许多相同的资源。多线程程序在结内存的使用效率要优于多进程程序。
2.python提供了完整的多线 ......
http://chardet.feedparser.org/ 自动检测编码
http://effbot.org/zone/celementtree.htm cElementTree
http://github.com/jaybaird/python-bloomfilter bloomfilter
http://docs.python.org/library/threading.html#threading.activeCount threading ......
在python中如何创建一个线程对象
如果你要创建一个线程对象,很简单,只要你的类继承threading.Thread,然后在__init__里首先调用threading.Thread的__init__方法即可
import threading
class mythread(threading.Thread):
def __init__(self, threadname):
& ......