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 = 0self.b = 1def next(self):self.a, self.b = self.b, self.a + self.breturn self.adef __iter__(self):return self#在迭代器和可迭代序列上进行迭代,还能把他们转换成序列  (实现了__iter__方法的对象是可迭代的,实现了next方法对象则是迭代器)
fibs = Fibs()
for f in fibs:if f > 10000:print fbreak>>>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 Truereturn 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, Extensionsetup(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的文档的功能还是比较强悍的,要从分的利用好

转载于:https://www.cnblogs.com/hdu-2010/p/4234035.html

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

  1. Python学习笔记13_模块

    Python学习笔记13_模块 文章目录 Python学习笔记13_模块 1.导入模块和的方法及使用 2.分层的文件系统中常用的包结构 3.OS 模块 4.sys 模块 5.math 模块 6.ran ...

  2. Python学习笔记:第三方模块2

    前言 最近在学习深度学习,已经跑出了几个模型,但Pyhton的基础不够扎实,因此,开始补习Python了,大家都推荐廖雪峰的课程,因此,开始了学习,但光学有没有用,还要和大家讨论一下,因此,写下这些帖 ...

  3. Python学习笔记:模块

    前言 最近在学习深度学习,已经跑出了几个模型,但Pyhton的基础不够扎实,因此,开始补习Python了,大家都推荐廖雪峰的课程,因此,开始了学习,但光学有没有用,还要和大家讨论一下,因此,写下这些帖 ...

  4. python学习笔记--迭代

    1.在Python中,迭代是通过for ... in来完成的,Python的for循环不仅可以用在list或tuple上,还可以作用在其他可迭代对象上,比如字典,字符串等 for ch in 'ABC ...

  5. Python学习笔记011_模块_标准库_第三方库的安装

    容器 -> 数据的封装 函数 -> 语句的封装 类 -> 方法和属性的封装 模块 -> 模块就是程序 , 保存每个.py文件 # 创建了一个hello.py的文件,它的内容如下 ...

  6. Python学习笔记——glob模块【文件、路径操作】

    最近做了一个将dicom文件转化为mhd文件的任务,由于要进行批量转化所以遍历文件夹必不可少,刚开始学习python编程,所以把用过的模块用法记录下来,以加深记忆,方便查阅,最后参考前人的博客做了gl ...

  7. Python 学习笔记 -- pickle模块,如何腌制泡菜(入门级)

    #关于腌菜的基础操作 #一般情况下学会腌菜的技术可以使文件大小更加小巧,更加持久. #下来是就是一些腌菜的基础用法 import pickle, os #在腌菜之前需要导入腌菜模块#实例一:这是一个保 ...

  8. Python学习笔记---day04进制和编码

    day04进制和编码 课程目标:讲解计算机中一些必备的常识知识,让学员了解一些常见名词背后的含义(重在理解) 课程概要: python代码的运行方式 进制 计算机的单位 编码 1. Python代码运 ...

  9. python学习笔记-基础、语句、编码、迭代器

    #python的优缺点 优点:Python简单优雅,尽量写容易看明白的代码,尽量写少的代码. 缺点:第一个缺点就是运行速度慢,和C程序相比非常慢,因为Python是解释型语言,你的代码在执行时会一行一 ...

  10. python学习笔记——hashlib模块

    上篇:https://blog.csdn.net/qq_42489308/article/details/89813895 hashlib Hash,译做"散列",也有直接音译为& ...

最新文章

  1. Android日志系统分析之日志设备驱动程序代码阅读
  2. wireshark抓包数据:理解与分析
  3. 牛客小白月赛12 I 华华和月月逛公园 (tarjian 求桥)
  4. java入栈_java中代码块的执行,也会有入栈的步骤吗?
  5. Websocket实现前后台通信,demo小测试
  6. 利用python自动发邮件
  7. Python基础--04
  8. STM32,仿照LL库,编写FLASH的LL库(内有完成代码)(STM32F0)
  9. PHP格式化 插件 vs code
  10. C++ sort函数(升序降序排列)
  11. “辉夜姬”:多利之后的动物明星
  12. iOS 联系在线客服功能
  13. 敏捷迭代就是小瀑布吗?为什么创业团队更敏捷?
  14. 针对list集合的操作,按照某一字段,对另一个字段进行归类
  15. html 设置min height,CSS中min-height使用技巧
  16. 为什么马斯克要说2022经济衰退?
  17. JDBC初学总结(四)
  18. 计算机二级vb常考知识点,全国计算机二级vb考试应考注意事项
  19. 电子计算机是机电一体化产品,关于机电一体化产品所有包括的范围
  20. 运输SaaS平台oTMS宣布完成2500万美元B轮融资

热门文章

  1. 女孩子适合学习前端开发吗?
  2. 执行计算机查错程序,计算机 每次启动过程中总会执行磁盘检查CHKDSK,什么问题???怎么处理??...
  3. 7位格雷码计算风向_七哥特刊|从二轮秀到队内得分王 格雷厄姆会新的蜂王吗?...
  4. html浮动跟随鼠标,jQuery 图片跟随鼠标浮动
  5. android o 编译及运行,【转】实践最有效的提高Android Studio运行、编译速度方案
  6. php地址选择插件,微信小程序中关于三级联动地址选择器的实例分享
  7. java locale中文_locale错误导致Java中文乱码错误的总结
  8. 松下机器人找原点步骤_桁架机器人在汽车座椅安装生产线中的应用
  9. C语言排序方法-----希尔排序
  10. keras笔记-模型保存以及tensorboard的使用