Python備忘錄-基礎

Python 基礎知識

Python命名規(guī)則

# 參考 PEP 8
# 類名
MyClass # bad : myClass,my_class
# 方法、模塊、包、變量名
var_underscore_separate # bad: varCamel,VarCamel
# 類中的私有變量
__var
# 屬性名
__var__

使用 future 的特性

導入__future__ 可以在python2中使用python3的一些特性,環(huán)境是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}

檢查是否可以調(diào)用

>>> 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的相關(guān)操作

>>> 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)
# 通過循環(huán)打印 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]
>>>

字典的相關(guān)操作


>>> 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}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容