Python学习笔记(迭代、模块扩展、GUI 、编码处理等)

PythonIDLE中的编码处理

http://www.tuicool.com/articles/NbyEBr

原文标题:Python中实际上已经得到了正确的Unicode或某种编码的字符,但是看起来或打印出来却是乱码

http://www.crifan.com/python_already_got_correct_encoding_string_but_seems_print_messy_code/?utm_source=tuicool

 

python写入带有中文字的字符串到文件

 

 

# -*- coding: utf-8 -*-

import codecs
content = u'你好,脚本分享网 sharejs.com'
f = codecs.open('c:/1.txt','w','utf-8')
f.write(content)

 

 

 

Python中迭代器

class Fibs:
    def __init__(self):
        self.a = 0
        self.b = 1
    def next(self):
        self.a, self.b = self.b, self.a + self.b
        return self.a
    def __iter__(self):
        return self
        
   
#在迭代器和可迭代序列上进行迭代,还能把他们转换成序列 (实现了__iter__方法的对象是可迭代的,实现了next方法对象则是迭代器) fibs
= Fibs() for f in fibs: if f > 10000: print f break >>>1597

 

 

Python迭代器使用(yield)

回溯法求解8皇后问题

#争端函数,问题描述:如何在棋盘上放置8个皇后,使其不会相互攻击

def
conflict(state, nextX): nextY = len(state) for i in range(nextY): if abs(state[i] -nextX) in (0, nextY - i): return True return False #回溯求解问题 def queens(num=8, state = ()): for pos in range(num): if not conflict(state, pos): if len(state) == num - 1: yield (pos, ) else: for result in queens(num, state + (pos, )): yield (pos, ) + result #打印解决方案 def prettyprint(solution): def line(pos, length = len(solution)): return ' . ' * (pos) + ' X ' + ' . ' * (length - pos - 1) for pos in solution: print line(pos) #随机打印一个解决方案 import random prettyprint(random.choice(list(queens(8))))

 

Python标准库函数充电(为已编号的行进行编号)

 

 

open文件后,记得close总是没有问题的。或者放入try finally语句中。或者使用

from __future__ import with_statement

with open(" ") as somefile:

   do_somnething(somefile)

 

 GUI章节中关于函数命名的一段话:

wx包中的方法都是以大写字母开头的,而这和Python的习惯是相反的。这样的做的原因是这些方法名和基础的C++包wxWidgets中的方法名都是对应的。

尽管没有正式的规则反对或者函数名以大写字母开头,但是规范的做法是为类保留这样的名字。

 

  • 扩展Python

扩展Python的C语言实现的方法(可以自己写代码,或者是使用一个叫做SWIG的工具),以及扩展其他两个Python实现——Jython和IronPython的方法。

除此之外,还有一些关于访问外部的其它方法的提示。

Jython对应Java, IronPython对应C#和其他的.NET语言。

扩展Python通常就是指扩展CPython,可以使用的自动化工具推荐使用SWIG(http://www.swig.org

(1) 为代码写接口文件。这很像C语言的头文件(而且,为了更简单,可以直接使用头文件)

(2)在接口文件上运行SWIG,自动生成部分C语言代码(包装代码)。

(3)把原来的C语言代码和产生的包装代码一起编译来产生共享库。

比如,一个简单的检测回文的C语言函数(palindrome.c)

#include <string.h>

int is_palindrome(char *text){
    int i = 0;
    int n = strlen(text);
    
    int ret = 1;
    for(i = 0; i <= n/2; i++){
        if(text[i] != text[n-i-1]){
            ret = 0;
            break;
        }
    }
    
    return ret;
}

还需要动手写一个文件(palindrome.i)

该文件只需要声明导出的所有的函数(和变量)即可。

除此之外,头部的一个单元(通过%{和}%来分界)内,可以指定包含头文件(比如本例中的string.h)以及在这之前的一个%module声明,即为模块定义一个名字。

%module palindrome
%{
#include <string.h>
%}

extern int is_palindrome(char *text);
  • 运行SWIG

swig -python palindrome.i

应该得到两个新文件,一个是palindrome_wrap.c,另一个是palindrome.py

  • 编译、链接以及使用

需要确保需要的文件能够顾找到,本文给出参考的绝对路径

$ gcc -c palindrome.c

$ gcc -user/include/python2.7 -c palindrome_wrap.c

$ gcc -shared palindrome.o, palindrome_wrap.o c:/python27/libs/libpython27.a  -o _palindrome.pyd

_palindrome.pyd, 就是得到的共享库,他能直接导入Python(放在当前的工作目录即可)。

 

 或者采用setup.py借用distutils工具一条编译命令即可

# -*- coding: utf-8 -*-
"""
Created on Wed Jan 28 16:54:09 2015

@author: Administrator
"""

from distutils.core import setup, Extension

setup(name = 'palindrome', version = '1.0',
      description = 'A simple example',
      author = 'Magnus Lie hetland',
      ext_modules = [Extension('_palindrome', ['palindrome.c', 'palindrome.i'])])


#命令 python setup.py build_ext --inplace
#要配置好环境变量和swig工具

得到

关于这个问题,有人在百度文库有详细的解释,不明白的请参考。

 

 

  • Python 中一切皆为对象

Every object has an identity, a type and a value. An object’s identity never changes once it has been created; you may think of it as the object’s address in memory. The ‘is‘ operator compares the identity of two objects; the id() function returns an integer representing its identity (currently implemented as its address). An object’s type is also unchangeable. [1] An object’s type determines the operations that the object supports (e.g., “does it have a length?”) and also defines the possible values for objects of that type. The type() function returns an object’s type (which is an object itself). The value of some objects can change. Objects whose value can change are said to be mutable; objects whose value is unchangeable once they are created are called immutable. (The value of an immutable container object that contains a reference to a mutable object can change when the latter’s value is changed; however the container is still considered immutable, because the collection of objects it contains cannot be changed. So, immutability is not strictly the same as having an unchangeable value, it is more subtle.) An object’s mutability is determined by its type; for instance, numbers, strings and tuples are immutable, while dictionaries and lists are mutable.

Objects are never explicitly destroyed; however, when they become unreachable they may be garbage-collected. An implementation is allowed to postpone garbage collection or omit it altogether — it is a matter of implementation quality how garbage collection is implemented, as long as no objects are collected that are still reachable


python是纯血统的面向对象的变成语言,与java不同。

为此我们可以看一下,我们知道java中int为基本数据类型,在持久化的时候,需要包装成Integer类对象。

但是在python中,一切皆对象。什么都是对象,包括你的代码。

为此我们进行一番探究。

1
2
3
4
5
6
7
8
# this is just begining
i=5
print hex(id(i))
print type(i)
i=10
print hex(id(i))
print type(i)
print  i.__add__(5
1
然后运行程序发现:

0x125a8c8
<type 'int'>
0x125a88c
<type 'int'>

15

通过阅读上面的英文部分,不难发现 

i的 id,value,以及type,所有对象都具有上述三种属性

然后查看帮助文档    

help> id
Help on built-in function id in module __builtin__:
id(...)
    id(object) -> integer
    Return the identity of an object.  This is guaranteed to be unique among
    simultaneously existing objects.  (Hint: it's the object's memory address.)

该函数返回的对象的内存地址值,通过该函数的声明不难发现i也是对象。

细心的读者可能会发现,此处发生了内存泄露,就i在指向10以后,对象5就不在被任何对象所引用。

不用担心,python的开发者早就想好处理方法,即对象的垃圾回收机制。

我们继续讨论int class 的详细情况

help> int
Help on class int in module __builtin__:
class int(object)
 |  int(x[, base]) -> integer
 |
 |  Convert a string or number to an integer, if possible.  A floating point
 |  argument will be truncated towards zero (this does not include a string
 |  representation of a floating point number!)  When converting a string, use
 |  the optional base.  It is an error to supply a base when converting a
 |  non-string.  If base is zero, the proper base is guessed based on the
 |  string content.  If the argument is outside the integer range a
 |  long object will be returned instead.
 |
 |  Methods defined here:
 |
 |  __abs__(...)
 |      x.__abs__() <==> abs(x)
 |
 |  __add__(...)
 |      x.__add__(y) <==> x+y
 |
 |  __and__(...)

 |      x.__and__(y) <==> x&y

此处省略了很多~~~~~~~~~~~~~~~~~~~··

通过帮助文档,我们知道int class 继承自object类,然后看到的该类的相关函数,

从该类的构造函数我们可以知道很多,

rint int(100)

1
2
3
4
print int('100',8)
# notice here ,something like typedef
integer=int
print type(integer)
1
2
3
print hex(id(integer)
# a new object
print type(integer('100',8))

输出内容如下:

100
64
<type 'type'>

0x1e1f35e0
<type 'int'>
需要注意的是:integer=int

该语句的作用相当于创建了int class的一个alias或是别名,这样你就可以用它来创建新的对象,很神奇吧

注意此时integer的值为int,id=0x1e1f35e0,type为type类型

下面顺藤摸瓜,自然想知道object类的定义是什么呢?

>>> help(object)
Help on class object in module __builtin__:
class object
 |  The most base type

从帮助文档我们仅能够推测数该class为基类,其它的信息就只能参阅官方文档了。搜索相关资料,发现

Python源码剖析的讲解还是比较有意思的,正在阅读中,后续会补充上~~~~~~~·····

同时也可以发现python的文档的功能还是比较强悍的,要从分的利用好

posted @ 2015-01-19 16:11  kongmeng  阅读(364)  评论(0编辑  收藏  举报