python的一些常用知识点备用

来源:互联网 发布:linux登陆ftp服务器 编辑:程序博客网 时间:2024/05/29 16:44

1)判断一个对象是否存在:变量,函数,类等。

1.1 方法使用内置函数locals():

>>> 'c' in locals().keys()Flase>>>def c():... pass>>> 'c' in locals().keys()True>>> 'b' in locals().keys()True>>> b = 1>>> 'b' in locals().keys()True

1.2 方法使用内置函数dir():

>>> 'd' in dir()False>>> d = 1>>> 'd' in dir()True>>> 'y' in dir()False>>> def y():...     pass>>> 'y' in dir()True

1.3 使用内置函数vars():

>>> vars().has_key('y')#y上面定义了。True>>> vars().has_key('z')False

2)文件遍历:
某个目录下文件的遍历,重命名以及删除等

In [1]: import osIn [2]: start = os.walk("/root/flask")In [3]: print start<generator object walk at 0x134f6e0>#放回的是一个生成器对象。#目录,子目录,目录下的文件In [4]: for x in start:   ...:     print x   ...:     ('/root/flask', ['MyApp'], ['d.zip'])('/root/flask/MyApp', ['templates', 'static'], ['login.py'])('/root/flask/MyApp/templates', [], ['index.html'])('/root/flask/MyApp/static', ['images', 'js', 'upload'], ['file.png', '123.jpg'])('/root/flask/MyApp/static/images', [], ['logo.png', 'bg.png', 'file.png', 'saber.ico', 'folder.png'])('/root/flask/MyApp/static/js', [], ['hello.js'])('/root/flask/MyApp/static/upload', [], ['out.xls', 'upload.xlsx'])

2)计算程序运行时间

来源:::::::::::::::::::::::
https://www.cnblogs.com/rookie-c/p/5827694.html
2。1)

[root@VM_131_54_centos chuanzhi]# cat th1.py import datetimestime = datetime.datetime.now()etime = datetime.datetime.now()print (etime-stime).seconds

2.2)

start = time.time()run_fun()end = time.time()print end-start

2.3)

start = time.clock()run_fun()end = time.clock()print end-start

方法1和方法2都包含了其他程序使用CPU的时间,是程序开始到程序结束的运行时间。

方法3算只计算了程序运行的CPU时间

swith…case的python实现:

<<编写高质量代码 改善python程序的91个建议>>一书中
python实现:

def f(n):    return {            0:"your typed zero.\n",            1:"you are in top.\n",            2:"n is an even number\n"            }.get(n,"only singel\n")

他使用了字典的特性,以跳转表的方法实现了swith…case..

python中的常量

使用类来处理:
http://blog.csdn.net/feimengjuan/article/details/50372750
关于setattr
https://www.cnblogs.com/elie/p/6685429.html

object.__setattr__(self, name, value)如果类自定义了__setattr__方法,当通过实例获取属性尝试赋值时,就会调用__setattr__。常规的对实例属性赋值,被赋值的属性和值会存入实例属性字典__dict__中。

新建一个const.py

class _const(object):    class ConstError(TypeError):pass    class ConstCaseError(ConstError):pass    def __setattr__(self,name,value):        if  self.__dict__.has_key(name):            raise self.ConstError,"Can't change const.%s"   %name        if  not name.isupper():            raise self.ConstCaseError,\                'const name "%s" is not all uppercase' %name        self.__dict__[name] = valueimport syssys.modules[__name__]=_const()

那么这样就可在其他文件中使用了。

>>>import const>>>const.I =1>>>const.I =2Traceback (most recent call last):  File "<stdin>", line 1, in <module>  File "const.py", line 8, in __setattr__    raise self.ConstError,"Can't change const.%s"%nameconst.ConstError: Can't change const.I引发一个异常
原创粉丝点击