美文网首页
Python 小知识

Python 小知识

作者: JaiUnChat | 来源:发表于2017-03-16 21:10 被阅读13次

1. if name == 'main' 作用

简单来说,就是这个语句只有在这个文件自己被执行的时候才会true执行,被别的文件引用的时候就不会执行。从而方便测试。
浅析python 中name = 'main' 的作用

2. GUI 之 Tkinter

例子

3.print和sys.stdout.write

print(obj)内部就是sys.stdout.\write(obj+'\n')

4.单引号和双引号

s1 = 'string'
s2 = "string"
s3 = '"' #被单引号包含时双引号不用转义
s4 = "'" #被双引号包含时单引号不用转义

5.With语句

with 语句执行紧跟着的对象的enter()方法,然后将返回值赋予as部分,最后执行exit()方法。

class Sample:
    def __enter__(self):
        return self

    def __exit__(self, type, value, trace):
        print "type:", type
        print "value:",  value
        print "trace:",  trace

    def do_something(self):
        bar = 1/0
        return bar + 10

with Sample() as sample:
    sample.do_something()

输出:

type: <type 'exceptions.ZeroDivisionError'>
value: integer division or modulo by zero
trace: <traceback object at 0x1004a8128>
Traceback
(most recent call last):
File "./with_example02.py",
line 19, in <module>
  sample.do_something()
File "./with_example02.py",
  line 15, in do_something
  bar = 1/0
ZeroDivisionError:
  integer division or modulo  by zero
6. 共享类变量
class Counter:
    count = 0    
    def __init__(self):
        print("Do a test")
    def plus(self):
        self.count = self.count + 1
        print(self.count)
a = counter()
b = counter()
a.plus()
b.plus()
// 1 
// 1


class Counter:
    count = 0    
    def __init__(self):
        print("Do a test")
    def plus(self):
        Counter.count = Counter.count + 1
        print(Counter.count)
a = counter()
b = counter()
a.plus()
b.plus()
// 1 
// 2

相关文章

  • Python3.0中nonlocal关键字和python2.xl

    python 应用小知识,Python3.0中nonlocal关键字和python2.xlist或dict。希望小...

  • Python小知识

    Python的优点:功能强大,开发效率高,应用广泛,易上手,语法简洁 用途:网页开发,可视化(GUI)界面开发,网...

  • python小知识

    关于变量:python与其他编程语言稍有不同,他不是把值存储在变量中更像是把名字贴在变量上去。 python如何产...

  • python小知识

    函数的可变参数 *args: 接受普通参数,以元祖形式保存。**kwargs:接受关键字参数,以字典形式保存。更新...

  • python小知识

    本文主要记录python中常用的知识点,每一条都针对一个小问题给出可行的解决方法。 目录: 1.打印格式控制 2....

  • Python 小知识

    1. if name == 'main' 作用 简单来说,就是这个语句只有在这个文件自己被执行的时候才会true执...

  • python 小知识

    验证浮点数相加等于另外一个浮点数: 列表变为索引 元素 字符编码转换 生成当前时间唯一订单号 将多个列表按位置组合...

  • python入门到放弃,人生苦短我用python

    加小编Python学习群:813542856可以获取数十套Python入门学习资料! Python基础知识: Py...

  • Python 小知识学习

    1. m = [0, 1, 2];print m[0]和print n[0:1]结果是不一样的,前者输出0,后者输...

  • Python-小知识

    概览 这篇文章主要用来存放我在工作中使用Python时的一些问题与收获 正文 Python中不允许使用数字打头命名...

网友评论

      本文标题:Python 小知识

      本文链接:https://www.haomeiwen.com/subject/jstsnttx.html