天天看點

python基礎知識踩點

1、注釋

在python中,注釋是以任何存在于#右側的文字,其主要作用是寫給程式讀者看的筆記。

例如
單行注釋
>>print("hello world") #這是一個注釋

多行注釋使用一對'''
'''
這是注釋
這是注釋
這是注釋
'''
           

2、Python2的中文編碼問題

python2中預設的編碼不支援中文,如果要在python2中支援中文,需要在.py檔案的開頭聲明使用的編碼。

在py檔案的開頭添加下面語句:
#coding=utf-8
也可以有另外一種聲明格式:
#-*- coding:utf-8 -*-
           

3、python2和python3中輸入功能不同

python2和python3中擷取輸入的方法不同,需要注意所有從鍵盤擷取的輸入都是字元串類型。

在python2中,擷取輸入的方法是:
>>>a = raw_input("請輸入内容:")

在python3中,擷取輸入的方法是:
>>>a = input("請輸入内容:")
           

4、變量類型轉換

5、"is"和"=="的差別

6、真除法和地闆除

在python中實際上有3種類型的除法,有2種不同的除法操作符,其中一種在python3中有了變化:

x / y

傳統除法和真除法。在python2.6或之前的版本中,這個操作對于整數會省去小數部分,對于浮點數會保持小數部分。在python3.0版本中将會變成真除法(無論任何類型都會儲存小數部分)

x // y

floor除法(地闆除)。在python2.6中新增的操作,在python2.6和python3.0中均能使用。這個操作不考慮操作對象的類型,總會省略結果的小數部分,剩下最小的能整除的整數部分。

python@ubuntu:~$ ipython3
Python 3.5.2 (default, Jul  5 2016, 12:43:10) 
In [1]: 10 / 4
Out[1]: 2.5

In [2]: 10 //4
Out[2]: 2

In [3]: 10 /4.0
Out[3]: 2.5

In [4]: 10 //4.0
Out[4]: 2.0

python@ubuntu:~$ ipython
Python 2.7.12 (default, Jul  1 2016, 15:12:24)
In [1]: 10 / 4
Out[1]: 2

In [2]: 10 / 4.0
Out[2]: 2.5

In [4]: 10 // 4
Out[4]: 2

In [5]: 10 // 4.0
Out[5]: 2.0

           

7、疊代器

可疊代對象:如果對象是實際儲存的序列,或者可以在可疊代工具環境中一次産生一個結果的對象,就可以看做是可疊代的,也就是疊代器。

可疊代協定:有__next__方法的對象會前進到下一個結果,而在一系列結果的末尾,則會引發StopIteration。在python中,任何這類對象都認為是可疊代的。任何這類對象能以for循環或者其他疊代工具周遊,因為所有疊代工具内部工作起來就是每次疊代中調用__next__,并且捕捉StopIteration異常來确定何時離開。

字元串疊代器
In [1]: for i in "abc":
   ...:     print(i)
   ...:     
a
b
c
檔案疊代器:
In [1]: f = open('script1.py')

In [2]: f.__next__()
Out[2]: 'import sys\n'

In [3]: f.__next__()
Out[3]: 'print(sys.path)\n'

In [4]: f.__next__()
Out[4]: 'x = 2\n'

In [5]: f.__next__()
Out[5]: 'print(2**10)\n'

In [6]: f.__next__()
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
<ipython-input-6-39ec527346a9> in <module>()
----> 1 f.__next__()

StopIteration:

           

手動疊代:iter和next

為了支援手動疊代代碼,python3提供了一個内置函數next,它會自動調用一個對象的__next__方法。給定一個可疊代對象x,調到next(x)等同于x.__next__(),但前者簡單得多。

例如,對于檔案的任何一種形式都可以使用
In [7]: f = open('script1.py')

In [8]: f.__next__()
Out[8]: 'import sys\n'

In [9]: f.__next__()
Out[9]: 'print(sys.path)\n'

In [10]: f = open('script1.py')

In [11]: next(f)
Out[11]: 'import sys\n'

In [12]: next(f)
Out[12]: 'print(sys.path)\n'

           

生成器都是 Iterator 對象,但 list 、 dict 、 str 雖然是 Iterable ,卻不是 Iterator 。

把 list 、 dict 、 str 等 Iterable 變成 Iterator 可以使用 iter() 函數:

In [26]: L = [11,22,33]

In [27]: I = iter(L)

In [28]: next(I)
Out[28]: 11

In [29]: next(I)
Out[29]: 22

In [30]: next(I)
Out[30]: 33

           

判斷一個資料類型是否是可疊代器對象。

可以被next()函數調用并不斷傳回下一個值的對象稱為疊代器:Iterator。

可以使用 isinstance() 判斷一個對象是否是 Iterator 對象:

In [39]: from collections import Iterator

In [40]: isinstance((x for x in range(10)),Iterator)
Out[40]: True

In [41]: isinstance([],Iterator)
Out[41]: False

In [42]: isinstance({},Iterator)
Out[42]: False

In [43]: isinstance("abc",Iterator)
Out[43]: False

In [44]: isinstance(100,Iterator)
Out[44]: False

In [45]: f = open('script1.py')

In [46]: isinstance(f,Iterator)
Out[46]: True

           

總結:

凡是可作用于 for 循環的對象都是 Iterable 類型;

凡是可作用于 next() 函數的對象都是 Iterator 類型

集合資料類型如 list 、 dict 、 str 等是 Iterable 但不是 Iterator ,不過可以通過 iter() 函數獲得一個 Iterator 對象。

8、動态添加屬性和方法

動态程式設計語言 是 進階程式設計語言 的一個類别,在計算機科學領域已被廣泛應用。它是一類 在運作時可以改變其結構的語言 :例如新的函數、對象、甚至代碼可以被引進,已有的函數可以被删除或是其他結構上的變化。動态語言目前非常具有活力。例如JavaScript便是一個動态語言,除此之外如 PHP 、 Ruby 、 Python 等也都屬于動态語言,而 C 、 C++ 等語言則不屬于動态語言。----來自 維基百科

在python中,可以在程式運作過程中添加屬性和方法:

添加屬性:
>>> class Person(object):
    def __init__(self, name = None, age = None):
        self.name = name
        self.age = age
>>> P = Person("小明", "24")
#在這裡,我們定義了1個類Person,在這個類裡,定義了兩個初始屬性name和age。
#如果我們想添加一個性别的屬性可以這樣做:
>>> P.sex = "male"
>>> P.sex
'male'
>>>

#如果要添加的屬性對于類的所有對象都适用,那麼可以将這個屬性綁定在類上
>>>> Person.sex = None #給類Person添加一個屬性
>>> P1 = Person("小麗", "25")#建立一個新對象
>>> print(P1.sex) #如果P1這個執行個體對象中沒有sex屬性的話,那麼就會通路它的類屬性
None #可以看到沒有出現異常
>>>
           

動态添加方法

>>> class Person(object):
    def __init__(self, name = None, age = None):
        self.name = name
        self.age = age
    def eat(self):
        print("eat food")


>>> def run(self, speed):
    print("%s在移動, 速度是 %d km/h"%(self.name, speed))


>>> P = Person("老王", 24)
>>> P.eat()
eat food
>>> 
>>> P.run()
Traceback (most recent call last):
  File "<pyshell#5>", line 1, in <module>
    P.run()
AttributeError: Person instance has no attribute 'run'
>>>
>>>
>>> import types
>>> P.run = types.MethodType(run, P)
>>> P.run(180)
老王在移動,速度是 180 km/h
           

既然給類添加方法,是使用"類名.方法名 = xxxx",那麼給對象添加一個方法也是類似的"對象.方法名 = xxxx"

完整代碼如下:

import types

#定義了一個類
class Person(object):
    num = 0
    def __init__(self, name = None, age = None):
        self.name = name
        self.age = age
    def eat(self):
        print("eat food")

#定義一個執行個體方法
def run(self, speed):
    print("%s在移動, 速度是 %d km/h"%(self.name, speed))

#定義一個類方法
@classmethod
def testClass(cls):
    cls.num = 100

#定義一個靜态方法
@staticmethod
def testStatic():
    print("---static method----")

#建立一個執行個體對象
P = Person("老王", 24)
#調用在class中的方法
P.eat()

#給這個對象添加執行個體方法
P.run = types.MethodType(run, P)
#調用執行個體方法
P.run(180)

#給Person類綁定類方法
Person.testClass = testClass
#調用類方法
print(Person.num)
Person.testClass()
print(Person.num)

#給Person類綁定靜态方法
Person.testStatic = testStatic
#調用靜态方法
Person.testStatic()
           

9、__slots__的作用

動态語言與靜态語言的不同:

動态語言:可以在運作的過程中,修改代碼。

靜态語言:編譯時已經确定好代碼,運作過程中不能修改。

如果我們想要限制執行個體的屬性怎麼辦?比如,隻允許對Person執行個體添加name和age屬性。

為了達到限制的目的,Python允許在定義class的時候,定義一個特殊的__slots__變量,來限制該class執行個體能添加的屬性:

>>> class Person(object):
    __slots__ = ("name", "age")

>>> P = Person()
>>> P.name = "老王"
>>> P.age = 20
>>> P.score = 100
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
AttributeError: Person instance has no attribute 'score'
>>>
           

注意:

使用__slots__要注意,__slots__定義的屬性僅對目前類執行個體起作用,對繼承的子類是不起作用的

In [67]: class Test(Person):
    ...:     pass
    ...:

In [68]: t = Test()
In [69]: t.score = 100
           

來源:

https://segmentfault.com/a/1190000017439131