Python备忘录-基础

作者: CoderMiner | 来源:发表于2017-02-06 14:30 被阅读62次

    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}
    

    相关文章

      网友评论

        本文标题:Python备忘录-基础

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