Python备忘录-基础

Python 基础知识

Python命名规则

# 参考 PEP 8
# 类名
MyClass # bad : myClass,my_class
# 方法、模块、包、变量名
var_underscore_separate # bad: varCamel,VarCamel
# 类中的私有变量
__var
# 属性名
__var__

使用 future 的特性

导入__future__ 可以在python2中使用python3的一些特性,环境是python2.7

# 参考 PEP 236
>>> print "Hello,world"
Hello,world
>>> from __future__ import print_function
>>> print "Hello,world"
  File "<stdin>", line 1
    print "Hello,world"
                      ^
SyntaxError: invalid syntax
>>> print("Hello,world")
Hello,world

>>> type("Hello")
<type 'str'>
>>> from __future__ import unicode_literals
>>> type("Hello")
<type 'unicode'>

>>> 1/2
0
>>> from __future__ import division
>>> 1/2
0.5

future 的具体的特性请参考 future

检查对象的属性

>>> dir(list)
['__add__', '__class__', ...]

定义 doc 方法

>>> def Example():
          """ This is an example function"""
          print "Example function"

>>> Example.__doc__
' This is an example function'

# or using help function
>>> help(Example)
Help on function Example in module __main__:

Example()
    This is an example function

>>>

检查实例的类型

>>> ex = 10
>>> isinstance(ex,int)
True

检查 Get、Set属性

>>> class Example(object):
    def __init__(self):
        self.name = "ex"
    def printex(self):
        print "This is an example"


>>> ex = Example()
>>> hasattr(ex,"name")
True
>>> hasattr(ex,"printex")
True
>>> hasatter(ex,"print")
>>> hasattr(ex,"print")
False
>>> getattr(ex,"name")
'ex'
>>> setattr(ex,"name",'example')
>>> ex.name
'example'

检查继承

>>> class Example(object):
    def __init__(self):
        self.name = "ex"
    def printex(self):
        print "This is an example"

>>> issubclass(Example,object)
True

检查所有的全局变量

globals() 方法返回一个字典

>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>, 'Example': <class '__main__.Example'>, 'ex': <__main__.Example object at 0x000000000349D160>, '__name__': '__main__', '__package__': None, '__doc__': None}

检查是否可以调用

>>> def fun():
    print 'I am callable'

>>> callable(a)
False
>>> callable(fun)
True

获取方法、类的名称

>>> class ExampleClass(object):
    pass

>>> def example_fun():
    pass

>>> ex = ExampleClass()
>>> ex.__class__.__name__
'ExampleClass'
>>> example_fun.__name__
'example_fun'

List的相关操作

>>> a = [1, 2, 3, 4, 5]
>>> a[0]
1
>>> a[-1]
5
>>> a[0:]
[1, 2, 3, 4, 5]
>>> a[:-1]
[1, 2, 3, 4]
>>> a[0:-1:2]
[1, 3]
>>> s = slice(0,-1,2)
>>> a[s]
[1, 3]
>>> s
slice(0, -1, 2)
# 通过循环打印 list的索引和元素值
>>> a = range(3)
>>> for idx,item in enumerate(a):
    print(idx,item)


(0, 0)
(1, 1)
(2, 2)
# 将两个list组成一个元组list
>>> a = [1, 2, 3, 4, 5]
>>> b = [2, 4, 5, 6, 8]
>>> zip(a,b)
[(1, 2), (2, 4), (3, 5), (4, 6), (5, 8)]
# List 过滤
>>> [x for x in range(5) if x > 1]
[2, 3, 4]
>>> predicate = lamba x : isinstance(x,int)
>>> l = ['1', '2', 3, 'Hello', 4]
>>> filter(predicate,l)
[3, 4]
# List 去重
>>> a = [1, 2, 3, 3, 3]
>>> list({_ for _ in a})
[1, 2, 3]
# 或者通过set去重
>>> list(set(a))
[1, 2, 3]
# list倒序
>>> a = [1, 2, 3, 4, 5]
>>> a[::-1]
[5, 4, 3, 2, 1]
>>>

字典的相关操作


>>> a = {"1":1, "2":2, "3":3}
>>> b = {"2":2, "3":3, "4":4}
# 获取所有的key
>>> a.keys()
['1', '3', '2']
# 将key和value组成一个元组list
>>> a.items()
[('1', 1), ('3', 3), ('2', 2)]
# 在两个字典中查找重复的key
>>> [_ for _ in a.keys() if _ in b.keys()]
['3', '2']
>>> c = set(a).intersection(set(b))
>>> list(c)
['3', '2']
# 更新字典
>>> a.update(b)
>>> a
{'1': 1, '3': 3, '2': 2, '4': 4}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • No.1 python交互界面(解释器)提示符 Python的交互界面有两种提示符,分别是主提示符“>>>”和次提...
    无聊的IT阅读 1,376评论 0 5
  • 1.元类 1.1.1类也是对象 在大多数编程语言中,类就是一组用来描述如何生成一个对象的代码段。在Python中这...
    TENG书阅读 1,325评论 0 3
  • # Python 资源大全中文版 我想很多程序员应该记得 GitHub 上有一个 Awesome - XXX 系列...
    aimaile阅读 26,599评论 6 427
  • 接上一篇 PS: 在本篇中 你会了解到: 1.Python3.5 在Linux平台上的安装步骤 2.Python...
    斐波那契的数字阅读 542评论 0 1
  • 淅淅沥沥的小雨下了一天一夜。 雨点敲打地面发出的唰唰的声响,就像一曲一个基调的催眠曲,加上昏蒙...
    4点半的恩赐阅读 280评论 0 0