6

python动态添加类属性、实例属性

 2 years ago
source link: https://www.hi-roy.com/posts/python%E5%8A%A8%E6%80%81%E6%B7%BB%E5%8A%A0%E7%B1%BB%E5%B1%9E%E6%80%A7%E5%AE%9E%E4%BE%8B%E5%B1%9E%E6%80%A7/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

python动态添加类属性、实例属性

2013-11-12

看高手写出来的东西果然能学到很多阿!!昨天学到了如何用OptionParser生成命令行帮助信息,本来今天是要从中学习doctest使用的,不过却发现了这样一段代码:

>>> import datetime
>>> logger = configLogger('test.log')
>>> time = datetime.datetime.now().strftime("%m%d%H%M%S")
>>> sq = mySqlite('test.db', logger, 1)
>>> table = 'd' + str(time)
>>> sq.create(table)
>>> tp = ThreadPool(5)
>>> def t():pass
>>> t.depth=1
>>> t.urlpth='http://www.baidu.com'
>>> t.logfile = 'test.log'
>>> t.loglevel = 1
>>> t.dbpth = 'test.db'
>>> t.key = 'test'
>>> d = Crawler(t, tp, table, logger)
>>> d.getPageSource(t.urlpth, t.key, t.depth)
True

doctest功能就是根据写的模仿终端输入的字符串来进行测试,猛一看到定义了一个函数并给函数添加属性最后当作参数传递时候十分不解,后来突然想起来 python中一切皆是对象 这句话后恍然大悟,这里作者把函数当作字典(或者说C中的结构体?)来用了!又学到一招,不过为什么他不直接传递个字典进去呢?等下午研究研究…

借此正好复习一下python中类对象、实例对象等基础知识吧,整理如下:

#coding=utf-8
class a():
    count = 0
    def __init__(self):
        self.cou = 0
        self.__class__.count = self.__class__.count + 1  #这里调用类属性
print dir(a)#输出里没有cou
print "~~~~~~~~~~~~~~~~"
aa = a()
aa.cou = 1
print aa.cou
print aa.count
print a.count
#print a.cou  用self修饰的是实例变量,类无法调用
print dir(aa)
print "~~~~~~~~~~~~~~~~~~~~"
ab = a()
ab.cou = 2
print ab.cou
print ab.count
print a.count
print dir(ab)
print "~~~~~~~~~~~~~~~~"
ac = a()
ac.cou = 3
print ac.cou
print a.count
ac.count = 30  #由于这里修改了类的count属性,所以count变成了实例属性
print ac.count
print a.count
print dir(ac)
print "~~~~~~~~~~~~~~~~~"
ad = a()
print aa.count
print ab.count
print ac.count #这里输出的不是4而是30,因为变成实例属性了,不再和其他实例公用类属性。
print "~~~~~~~~~~~~~~~~~~~~"
a.ex =  0  #动态添加一个类属性,所有对象共用
print dir(a)
print dir(aa)
print dir(ab)
print dir(ac)
def prints(self):    #记得添加self参数,是实例才能调用
    print "in class function"
    print self.cou,self.ex
a.prin = prints #动态添加函数,共用
print dir(a)
#a.prin()  类无法调用
aa.prin()
ab.prin()
ac.prin()
ad.prin = lambda : "new function"#这里把实例方法变成了普通函数
print ad.prin()
print dir(ad)
print type(aa.prin)  #<type 'instancemethod'>
print type(ad.prin)  #<type 'function'>
print "~~~~~~~~~~~~~~~~~~~"
def fun():
    '''is a function'''
    print "in fun"
def funs():
    print "in funs"
fun()  #函数也是对象,可以动态添加属性,可以和原有的__doc__一类的属性对比。
print fun.___doc__
fun.x = 1
print fun.x
fun.pr = funs
fun.pr()

看样子基础还是不够牢固阿,得加强基础的复习哈~


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK