def main(): print("This is the test of test() in hello.py: ") hello.test() print("This is the test of main() in hello.py: ") hello.main() print("This is the test of class Hello in hello.py: ") tmp = hello.Hello() tmp.show_string() print("This is the test of class Hello via \"from hello import Hello\"") tmp = Hello() tmp.show_string()
import hello import sys hello.test(sys.argv)
import os import qrcode from PIL import Image from hello import test # Problem1 print(os.getcwd()) # Problem2 test() # Problem3 img = Image.open("起风了.jpg") img.show() # Problem4 img_qrcode = qrcode.make(r"https:\\bilibili.com") img_qrcode.show()
#!/usr/bin/env python # -*- coding: utf-8 -*- # __author__ = 'wuyuxi' import hello hello.test() # 引入模块 # 别名引入 设置引入优先级 增强Python不同版本的一直性 try: import cStringIO as StringIO except ImportError: # 导入失败会捕获到ImportError import StringIO _xxx, __xx = (7, 8) # private变量 from pic import Image im = Image.open('test.png') print im.format, im.size, im.mode im.thumbnail((200, 100)) im.save('thumb.jpg', 'JPEG')
# 3.如果是脚本一:运行命令'python setup.py build'来进行编译 # 如果是脚本二:运行命令'python setup.py build_ext --inplace'来进行编译 # 然后会在当前目录下会生成hello.c文件(hello.pyx转换过来的C代码)和一个build目录 # build目录中有hello.cpython-36m-x86_64-linux-gnu.so文件(python经过cython编译之后的模块) # 注意:.so文件就是经过cython编译后的用来替代原来.pyx文件的,即编译产生.so文件后实际就不再需要.pyx文件了 # 一定要把.so文件从build目录移动到和.pyx文件同一目录下,否则其他调用它的代码会找不到它 # 另外编译除了产生.so文件之外还会产生很多其他的文件,都是不需要的 # 4.在其他python代码或会话中直接调用hello.pyx中的函数 from hello import test from datetime import datetime if __name__ == '__main__': time_1 = datetime.now() for num in range(30000): test(num) time_2 = datetime.now() print('run time:', time_2 - time_1) # 纯python代码直接运行的效果: # run time: 0:00:17.871023 # 用cython编译后运行的效果: # run time: 0:00:09.096707 # --------------------------------------------------------------------------------------------- # 进一步提升性能: # 简单的用cython对代码进行编译可以提高10%-50%的性能,但如果在代码中声明函数和变量类型可以提升更大的性能 # 注意:尤其是在for循环中被多次调用的变量在声明变量类型后对性能的提升更大 # 加入静态变量类型后的hello.pyx代码 def test(int num):
for i in range(n): for j in range(n): s += i * j return s cython_time = [] cython_res = [] python_time = [] python_res = [] eps = 1e-10 for i in range(10, 15): n = 2 ** i tic = time.time() cython_res.append(test(n)) toc = time.time() cython_time.append(toc- tic) tic = time.time() python_res.append(py_test(n)) toc = time.time() python_time.append(toc- tic) print("cython_time: {}".format(cython_time)) print("python_time: {}".format(python_time)) print("cython_res: {}".format(cython_res)) print("python_res: {}".format(python_res)) print("if cython_res == python_res ---> {}".format(cython_res == python_res)) print(np.array(python_time) / (np.array(cython_time) + eps))
# -*- coding: utf-8 -*- """ @author: Manvel Arutiunov """ import my_math as m import hello as h i = 0 j = 2 strn = '' print(h.test()) my_list = ['нулевой', 'первый', 'второй', 'третий', 'четвертый', 'пятый', 'шестой', 'седьмой', 'восьмой', 'девятый'] while (i <= 20): strn = 'Элемент: ' + '"' + my_list[m.mod(i,j)] + '", как остаток от деления ' + str(i) + ' на ' + str(j) print(strn) i += 1
def test(): args = sys.argv if len(args)==1: print('Hello, world!') elif len(args)==2: print('Hello, %s!' % args[1]) else: print('Too many arguments!') if __name__=='__main__': test() import hello 运行:hello.test() 正常的函数和变量名是公开的(public),可以被直接引用 __xxx__这样的变量是特殊变量,可以被直接引用,但是有特殊用途, 比如__author__,__name__ 模块定义的文档注释也可以用特殊变量__doc__访问 _xxx和__xxx这样的函数或变量就是非公开的(private) Python并没有一种方法可以完全限制访问private函数或变量 外部不需要引用的函数全部定义成private
# f1() # f2() # print int('11',base=2) def int2(x,base=2): return int(x,base) # print int2('10',2) intFor2 = functools.partial(int, base=2) # print intFor2('10') max2 = functools.partial(max,10) args = (2,5,6) # print max2(*args) print hello.test()
... def f(j): ... def g(): ... return j*j ... return g ... fs.append(f(i)) #f(i) -> a j=i, g connect to that j,,each time j is a different j ... return fs ... >>> f1, f2, f3 = count() >>> f1() 1 >>> f2() 4 >>> f3() 9 unnamed function >>> map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]) [1, 4, 9, 16, 25, 36, 49, 64, 81] 通过对比可以看出,匿名函数lambda x: x * x实际上就是: def f(x): return x * x 由于函数也是一个对象,而且函数对象可以被赋值给变量,所以,通过变量也能调用该函数。 >>> def now(): ... print '2013-12-25' ... >>> f = now >>> f() 2013-12-25 函数对象有一个__name__属性,可以拿到函数的名字: >>> now.__name__ 'now' >>> f.__name__ 'now' //decorator import functools def log(func): @functools.wraps(func) def wrapper(*args, **kw): print 'call %s():' % func.__name__ return func(*args, **kw)//执行待装饰函数 return wrapper @log def now(): print '2013-12-25' ~~把@log放到now()函数的定义处,相当于执行了语句: now = log(now) now指向了log返回的wrapper,且wrappre改了名字为now @log('execute') def now(): print '2013-12-25' 和两层嵌套的decorator相比,3层嵌套的效果是这样的: def log(text): def decorator(func): def wrapper(*args, **kw): print '%s %s():' % (text, func.__name__) return func(*args, **kw) return wrapper return decorator >>> now = log('execute')(now) 偏函数 关键字函数 >>> int('12345') 12345 但int()函数还提供额外的base参数,默认值为10。如果传入base参数,就可以做N进制的转换: >>> int('12345', base=8) 5349 >>> int('12345', 16) 74565 import sys 导入sys模块后,我们就有了变量sys指向该模块,利用sys这个变量,就可以访问sys模块的所有功能。 #!/usr/bin/env python # -*- coding: utf-8 -*- ' a test module ' __author__ = 'Michael Liao' import sys def test(): args = sys.argv if len(args)==1: print 'Hello, world!' elif len(args)==2: print 'Hello, %s!' % args[1] else: print 'Too many arguments!' if __name__=='__main__': test() 当我们在命令行运行hello模块文件时,Python解释器把一个特殊变量__name__置为__main__,而如果在其他地方导入该hello模块时,if判断将失败,因此,这种if测试可以让一个模块通过命令行运行时执行一些额外的代码,最常见的就是运行测试。 我们可以用命令行运行hello.py看看效果: $ python hello.py Hello, world! $ python hello.py Michael Hello, Michael! 如果启动Python交互环境,再导入hello模块: $ python Python 2.7.5 (default, Aug 25 2013, 00:04:04) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import hello >>> 导入时,没有打印Hello, word!,因为没有执行test()函数。 调用hello.test()时,才能打印出Hello, word!: >>> hello.test() Hello, world! 别名 try: import cStringIO as StringIO except ImportError: # 导入失败会捕获到ImportError import StringIO 这样就可以优先导入cStringIO。如果有些平台不提供cStringIO,还可以降级使用StringIO。导入cStringIO时,用import ... as ...指定了别名StringIO,因此,后续代码引用StringIO即可正常工作。 还有类似simplejson这样的库,在Python 2.6之前是独立的第三方库,从2.6开始内置,所以,会有这样的写法: try: import json # python >= 2.6 except ImportError: import simplejson as json # python <= 2.5 OO use object to imp func ,use func to imp class class Student(object): def __init__(self, name, score): self.name = name self.score = score def print_score(self): print '%s: %s' % (self.name, self.score) 和静态语言不同,Python允许对实例变量绑定任何数据,也就是说,对于两个实例变量,虽然它们都是同一个类的不同实例,但拥有的变量名称都可能不同: >>> bart = Student('Bart Simpson', 59) >>> lisa = Student('Lisa Simpson', 87) >>> bart.age = 8 >>> bart.age 8 >>> lisa.age Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'Student' object has no attribute 'age' 如果要让内部属性不被外部访问,可以把属性的名称前加上两个下划线__,在Python中,实例的变量名如果以__开头,就变成了一个私有变量(private),只有内部可以访问,外部不能访问,所以,我们把Student类改一改: class Student(object): def __init__(self, name, score): self.__name = name self.__score = score def print_score(self): print '%s: %s' % (self.__name, self.__score) 需要注意的是,在Python中,变量名类似__xxx__的,也就是以双下划线开头,并且以双下划线结尾的,是特殊变量,特殊变量是可以直接访问的,不是private变量,所以,不能用__name__、__score__这样的变量名。 有些时候,你会看到以一个下划线开头的实例变量名,比如_name,这样的实例变量外部是可以访问的,但是,按照约定俗成的规定,当你看到这样的变量时,意思就是,“虽然我可以被访问,但是,请把我视为私有变量,不要随意访问”。 双下划线开头的实例变量是不是一定不能从外部访问呢?其实也不是。不能直接访问__name是因为Python解释器对外把__name变量改成了_Student__name,所以,仍然可以通过_Student__name来访问__name变量: >>> bart._Student__name 'Bart Simpson' 但是强烈建议你不要这么干,因为不同版本的Python解释器可能会把__name改成不同的变量名。 总的来说就是,Python本身没有任何机制阻止你干坏事,一切全靠自觉。 多态 def run_twice(animal): animal.run() animal.run() >>> run_twice(Dog()) Dog is running... Dog is running... >>> run_twice(Animal()) Animal is running... Animal is running... >>> run_twice(Tortoise()) Tortoise is running slowly... Tortoise is running slowly... 你会发现,新增一个Animal的子类,不必对run_twice()做任何修改,实际上,任何依赖Animal作为参数的函数或者方法都可以不加修改地正常运行,原因就在于多态。 多态的好处就是,当我们需要传入Dog、Cat、Tortoise……时,我们只需要接收Animal类型就可以了,因为Dog、Cat、Tortoise……都是Animal类型,然后,按照Animal类型进行操作即可。由于Animal类型有run()方法,因此,传入的任意类型,只要是Animal类或者子类,就会自动调用实际类型的run()方法,这就是多态的意思 >>> import types >>> type('abc')==types.StringType True >>> type(u'abc')==types.UnicodeType True >>> type([])==types.ListType True >>> type(str)==types.TypeType True >>> a = Animal() >>> d = Dog() >>> h = Husky() >>> isinstance(h, Husky) True 能用type()判断的基本类型也可以用isinstance()判断: >>> isinstance('a', str) True >>> isinstance(u'a', unicode) True >>> isinstance('a', unicode) False 并且还可以判断一个变量是否是某些类型中的一种,比如下面的代码就可以判断是否是str或者unicode: >>> isinstance('a', (str, unicode)) True >>> isinstance(u'a', (str, unicode)) True /////////获得对象的所有属性和方法 使用dir() 如果要获得一个对象的所有属性和方法,可以使用dir()函数,它返回一个包含字符串的list,比如,获得一个str对象的所有属性和方法: >>> dir('ABC') ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '_formatter_field_name_split', '_formatter_parser', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] >>> hasattr(obj, 'x') # 有属性'x'吗? True >>> obj.x 9 >>> hasattr(obj, 'y') # 有属性'y'吗? False >>> setattr(obj, 'y', 19) # 设置一个属性'y' >>> hasattr(obj, 'y') # 有属性'y'吗? True >>> getattr(obj, 'y') # 获取属性'y' 19 >>> obj.y # 获取属性'y' 19 //获得对象的方法:或属性 //测试对象信息 >>> hasattr(obj, 'power') # 有属性'power'吗? True >>> getattr(obj, 'power') # 获取属性'power' <bound method MyObject.power of <__main__.MyObject object at 0x108ca35d0>> >>> fn = getattr(obj, 'power') # 获取属性'power'并赋值到变量fn >>> fn # fn指向obj.power <bound method MyObject.power of <__main__.MyObject object at 0x108ca35d0>> >>> fn() # 调用fn()与调用obj.power()是一样的 81 可以传入一个default参数,如果属性不存在,就返回默认值: >>> getattr(obj, 'z', 404) # 获取属性'z',如果不存在,返回默认值404 404 /////@property class Student(object): @property def birth(self): return self._birth @birth.setter def birth(self, value): self._birth = value @property def age(self): return 2014 - self._birth 上面的birth是可读写属性,而age就是一个只读属性,因为age可以根据birth和当前时间计算出来。 __slot__ 限制绑定 正常情况下,当我们定义了一个class,创建了一个class的实例后,我们可以给该实例绑定任何属性和方法,这就是动态语言的灵活性。先定义class: >>> class Student(object): ... pass ... 然后,尝试给实例绑定一个属性: >>> s = Student() >>> s.name = 'Michael' # 动态给实例绑定一个属性 >>> print s.name Michael 还可以尝试给实例绑定一个方法: >>> def set_age(self, age): # 定义一个函数作为实例方法 ... self.age = age ... >>> from types import MethodType >>> s.set_age = MethodType(set_age, s, Student) # 给实例绑定一个方法 >>> s.set_age(25) # 调用实例方法 >>> s.age # 测试结果 25 ///动态绑定 //////////给类动态绑定方法:class Student 1MethodType >>> def set_score(self, score): ... self.score = score ... >>> Student.set_score = MethodType(set_score, None, Student) 2直写 直接类名.字段 = method class A(object): pass #要给A加一个属性score,值为60 A.score=60 这样一来,A的所有实例及A子类的所有实例都有属性score且值为60 这个score可以等于一个方法,比如现在有个方法fuc #注意,如果要让这个方法可以被额外赋予到类上,方法的写法必须跟类里面的方法的写法一 致,即第一个参数为self def fuc(self,arg): print arg #给类A增加方法fuc A.score=fuc 3setattr setattr( A, 'd', 1) 或者 setattr( a1.__class__, 'd', 1) //////////给实例绑定 1MethodType >>> def set_age(self, age): # 定义一个函数作为实例方法 ... self.age = age ... >>> from types import MethodType >>> s.set_age = MethodType(set_age, s, Student) # 给实例绑定一个方法 >>> s.set_age(25) # 调用实例方法 >>> s.age # 测试结果25 2 直写 a1 = A() a1.c = 1 这里我们定义了一个类A,还有一个实例a1。a1.c = 1 只是增加实例的属性而不是增加类的属性。 3setattr(obj, 'y', 19) setattr似乎只能绑定属性,无法绑定方法 >>> setattr(obj, 'y', 19) # 设置一个属性'y' >>> hasattr(obj, 'y') # 有属性'y'吗? True >>> getattr(obj, 'y') # 获取属性'y' 19 >>> obj.y # 获取属性'y' 19 由于实例属性优先级比类属性高,因此,它会屏蔽掉类的name属性 为了达到限制的目的,Python允许在定义class的时候,定义一个特殊的__slots__变量,来限制该class能添加的属性: >>> class Student(object): ... __slots__ = ('name', 'age') # 用tuple定义允许绑定的属性名称 ... 然后,我们试试: >>> s = Student() # 创建新的实例 >>> s.name = 'Michael' # 绑定属性'name' >>> s.age = 25 # 绑定属性'age' >>> s.score = 99 # 绑定属性'score' Traceback (most recent call last): File "<stdin>", line 1, in <module> AttributeError: 'Student' object has no attribute 'score' __iter__ class Fib(object): def __init__(self): self.a, self.b = 0, 1 # 初始化两个计数器a,b def __iter__(self): return self # 实例本身就是迭代对象,故返回自己 def next(self): self.a, self.b = self.b, self.a + self.b # 计算下一个值 if self.a > 100000: # 退出循环的条件 raise StopIteration(); return self.a # 返回下一个值 __getitem__ 要表现得像list那样按照下标取出元素,需要实现__getitem__()方法: class Fib(object): def __getitem__(self, n): a, b = 1, 1 for x in range(n): a, b = b, a + b return a 现在,就可以按下标访问数列的任意一项了: >>> f = Fib() >>> f[0] 1 >>> f[1] 1 >>> f[2] 2 >>> f[3] 3 >>> f[10] 89 >>> f[100] 573147844013817084101 __getattribute__ rest api error and debug try: print 'try...' r = 10 / 0 print 'result:', r except ZeroDivisionError, e: print 'except:', e finally:
# -*- coding: utf-8 -*- # @Author: cbbfcd # @Date: 2017-08-28 13:46:35 # @Last Modified by: cbbfcd # @Last Modified time: 2017-08-28 14:47:10 # 模块 import sys print(sys.path) print(dir(sys)) # 引入模块测试 import hello hello.test() # hello world! print(hello.__name__,hello.__author__) # hello huangteng
#!/usr/bin/env python # -*- coding:utf-8 -*- import hello from define_fun import greeting from define_fun import Student from define_fun import Student1 from define_fun import Dog from define_fun import Cat from define_fun import run_twice from define_fun import Animal from define_fun import Tortoise hello.test() #####can't bring argument print(greeting('Minger')) print(greeting('A')) ###############################################test class bart = Student('Bart Simpson', 59) lisa = Student('Lisa Simpson', 87) bart.print_score() lisa.print_score() print(bart.get_grade()) bart.name = 'Minger' bart.score = 100 bart.print_score() minger = Student1('Minger Zhang', 100) minger.print_score() #print(minger.__name)
Hello, Michael! 如果启动Python交互环境,再导入hello模块: $ python3 Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 23 2015, 02:52:03) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import hello >>> 导入时,没有打印Hello, word!,因为没有执行test()函数。 调用hello.test()时,才能打印出Hello, word!: >>> hello.test() Hello, world! #作用域 在一个模块中,我们可能会定义很多函数和变量,但有的函数和变量我们希望给别人使用,有的函数和变量我们希望仅仅在模块内部使用。在Python中,是通过_前缀来实现的。 正常的函数和变量名是公开的(public),可以被直接引用,比如:abc,x123,PI等; 类似__xxx__这样的变量是特殊变量,可以被直接引用,但是有特殊用途,比如上面的__author__,__name__就是特殊变量,hello模块定义的文档注释也可以用特殊变量__doc__访问,我们自己的变量一般不要用这种变量名; 类似_xxx和__xxx这样的函数或变量就是非公开的(private),不应该被直接引用,比如_abc,__abc等; 之所以我们说,private函数和变量“不应该”被直接引用,而不是“不能”被直接引用,是因为Python并没有一种方法可以完全限制访问private函数或变量,但是,从编程习惯上不应该引用private函数或变量。 private函数或变量不应该被别人引用,那它们有什么用呢?请看例子:
#枚举 from enum import Enum,unique Month=Enum("Month",('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')) print(Month.Jan.value) @unique class WeekDay(Enum): Sun = 0 # Sun的value被设定为0 Mon = 1 Tue = 2 Wed = 3 Thu = 4 Fri = 5 Sat = 6 print("WeekDay Sun",WeekDay.Sun.value,WeekDay['Sun'].value) #使用原类 print("###使用原类####") import hello hello.test() print(type(hello)) print(type(hello.Hello)) h=hello.Hello() print(type(h)) print("##############原类########################") Hello=type("Hello",(object,),dict(hello=lambda name:print("hello:",name))) #print(type(Hello)) #hl=Hello() #print(type(hl),dir(h1)) #h1.hello("chenmd")
Hello, world! $ python hello.py Michael #运行python hello.py Michael获得的sys.argv就是['hello.py', 'Michael]。 Hello, Michael! 如果启动Python交互环境,再导入hello模块: $ python3 Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 23 2015, 02:52:03) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import hello >>> 导入时,没有打印Hello, word!,因为没有执行test()函数。 调用hello.test()时,才能打印出Hello, word!: >>> hello.test() Hello, world! # 作用域: 正常的函数和变量名是公开的(public),可以被直接引用,比如:abc,x123,PI 似__xxx__这样的变量是特殊变量,可以被直接引用,但是有特殊用途,比如上面的__author__,__name__就是特殊变量, hello模块定义的文档注释也可以用特殊变量__doc__访问,我们自己的变量一般不要用这种变量名 类似_xxx和__xxx这样的函数或变量就是非公开的(private),不应该被直接引用,比如_abc,__abc 之所以我们说,private函数和变量“不应该”被直接引用,而不是“不能”被直接引用,是因为Python并没有一种方法可以完全限制访问private函数或变量,但是,从编程习惯上不应该引用private函数或变量 private函数或变量不应该被别人引用,那它们有什么用呢?请看例子: >>> def _private_1(name): return 'Hello, %s' % name
import hello print(hello.test())
def post(self): dataRecieved = tornado.escape.xhtml_escape(self.request.body) outputReturned = hello.test(dataRecieved) self.write(json.dumps(outputReturned))
def today2(): print('2015-3-25') today2() print(int('123456')) print(int('100000', base=2)) # base=N 转换成几进制, 打印出还是以十进制的方式, 也就是字符串以N进制的形式转换成十进制 int2 = functools.partial(int, base=2) print(int2('100')) hello.test() print(hello.__doc__) print(hello.__author__) # print(sys.path) class Student(object): # Student 类名 object:Student所继承的父类 def __init__(self, name=None, score=0): self.name = name self.score = score def print_score(self): print('%s: %s' % (self.name, self.score))
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Date : 2018-07-12 10:57:44 # @Author : uhover ([email protected]) # @Link : http://www.baidu.com/ # @Version : $Id$ from __future__ import division import os import sys # import hello # hello.test() try: import hello as test except ImportError: import test test.test() print test.__author__ print test.greeting('na') print test._func1('name') print sys.path print 10 // 3