1. 程式人生 > >python知識整理(class類及一些函式介紹)_5

python知識整理(class類及一些函式介紹)_5

#!/usr/bin/env python
# -*- conding:utf-8

class 定義一個類:  廣泛的分類,每個分類裡有自己的屬性和功能:比如有人和動物兩類,而人可以打拳,說話等待:
用class定義一個類,首字母推薦大寫,冒號不能少:
class Calculator:
比如  Calculator  
class 可以先定義自己的屬性,比如屬性的名稱:  name='Good Calculator'
class 後面還可以跟 def 函式, 輸出print(x+y)
def add(self,x,y):
注意這裡的 (self,x,y) 是預設值:

註釋: 定義自變數cal等於 Calculator 要加括號"()" 

cal=Calculator()
否則執行下面函式會出現錯誤:

內容:

class Calculator:
    name = 'Good Calculator'
    price = 18
    def add(self,x,y):
        print(self.name)
        result = x + y 
        print(resulut)
    def min(self,x,y):
        result = x - y 
        print(resulut)
    def times(self,x,y):
        result(self,x,y):

        print(result)
    def divide(self,x,y):
        result = x / y
        print(reslut)
    
    
cal = Calculator()

cal.               // tab 補全
cal.
cal.add     cal.divide  cal.min     cal.name    cal.price   cal.times

請問為什麼,class裡一定要用self~?
呼叫class裡面的屬性或功能, 需要從self才能調用出來。

class 類 init 功能:   註釋,  這是是雙下劃線:

除了可以新增屬性,功能之外,還可以有內建的一些引數。
__init__ 可以理解成初始化class的變數,可以在執行時,給初始值賦值:    initial

def __init__(self,name,price,height,width,weight):       // 裡面新增的是一些引數等:

固有屬性: 函式外定義, class 裡面

自定義屬性: 呼叫時自己新增的引數:     //比較常用的

自定義屬性 優選與 固有屬性,同時存在,以自定義的為準,如下 "bad calculator"

預設引數:  同函式一樣,在定義函式時定義:

class Calculator:
    name = 'Good calculator'
    price =18
    def __init__(self,name,price,height,width,weight):
        self.name = name
        self.price = price
        self.h = height
        self.wi = width
        self.we = weight
    
執行:
c = Calculator('bad calculator',18,15,23,24)             //  六個引數
c.
c.h      c.name   c.price  c.we     c.wi     

c.name
'bad calculator'

也可以設定預設引數: 同函式設定一樣:

class calculator():
    def __init__(self,name,price,height=16,width=22,weight=32):
        self.name = name
        self.price = price
        self.h = height
        self.wi = width
        self.we = weight
        self.add(1,2)
    def add(self,x,y):
        result = x + y
        print(print result)
    def minus(self,x,y):
        result = x - y
        print(result)
    def times(self,x,y):
        print(x*y)
    def divide(self,x,y):
        result(x / y)
        print(result)
    

c = Calculator('bad calculator',18)
3

c.
c.add    c.h      c.name   c.price  c.we     c.wi    

c.name
'bad calculator'

c.wi
29

c.add(2,3)
5

註釋:這些預設值是可以更改的:
c.we
22
  
c.we = 16

c.we
16

c.we = 4

c.we
4

input函式:    一般input多用在 if 判斷中: 如判斷分數之類的:
兩個形式:
raw_input()      接收的是一個表示式,適用於數字,如果輸入字串則需要用引號:
input()          接收的是字串,無論輸入什麼都是字串:

a = input('please input a number :')
please input a number :1
In [37]: type(a)
Out[37]: int

In [38]: a = input('please input a number :')
please input a number :'abc'
In [39]: type(a)
Out[39]: str

In [40]: b = raw_input('please input number :')
please input number :123
In [41]: type(b)
Out[41]: str

In [42]: b = raw_input('please input number :')
please input number :'abc'
In [43]: type(b)
Out[43]: str

a_input = input('pelase input a number: ')
pelase input a number: 34
print('This number is: ', a)
34

[root@fenye2019 20190621]# cat 8.py 
#!/usr/bin/env python
# ----conding:utf-8 ----
a_input = int(input('please input a nubmer: '))
if a_input == 1:
    print('this is own')
elif a_input == 2:
    print('this is two')
else:
    print('good luck')
[root@fenye2019 20190621]# python 8.py 
please input a nubmer: 2
this is two
[root@fenye2019 20190621]# python 8.py 
please input a nubmer: 1
this is own
[root@fenye2019 20190621]# python 8.py 
please input a nubmer: 5
good luck

練習: 輸入對應分數列印成績:         score
[root@fenye2019 20190621]# cat 9.py 
#!/usr/bin/env python
# ---- conding:utf-8 ----
score = int(input('Please input a number: '))
if score >= 90:
    print('This i very good')
elif score >= 80:
    print('This is good')
elif score >= 60:
    print('This is jige')
else:
    print('This is flase')

[root@fenye2019 20190621]# python 9.py 
Please input a number: 90
This i very good
[root@fenye2019 20190621]# python 9.py 
Please input a number: 85
This is good
[root@fenye2019 20190621]# python 9.py 
Please input a number: 62         
This is jige
[root@fenye2019 20190621]# python 9.py 
Please input a number: 15
This is flase

迭代輸出:
元組 tuple    列表(可變的)  list  字串  都是序列
序列支援切片, 索引, if  for 等:
索引: 是取一個字元    //  0表示第一個的元素,           -l表示最後一個元素
切片: 是取一組字元

l
Out[74]: [6, [4, 'b', 6], ['python', 'python', 'linux']]
In [75]: print(l[0])
6
In [76]: print(l[2])
['python', 'python', 'linux']

print(l[0:2])
[6, [4, 'b', 6]]
In [78]: print(l[:2])
[6, [4, 'b', 6]]
In [79]: print(l[:])
[6, [4, 'b', 6], ['python', 'python', 'linux']]

元組:  元素可以是字串,整數,元組,列表
t = ('fenye',25,(1,2,3),[4,'fy',5])
列表:
l = ['fenye',25m(1,2,3),[4,'b',5]]

分別列印:
In [4]: for tuple in t:
   ...:     print tuple
   ...:     
fenye
25
(1, 2, 3)
[4, 'b', 6]

In [5]: for list in l:
   ...:     print list
   ...:     
fenye
25
(1, 2, 3)
[4, 'b', 6]

l
['fenye', 25, (1, 2, 3), [4, 'b', 6]]

Ifor index in range(len(l)):
    print('index=',index,'number is=',l[index])
 
('index=', 0, 'number is=', 'fenye')
('index=', 1, 'number is=', 25)
('index=', 2, 'number is=', (1, 2, 3))
('index=', 3, 'number is=', [4, 'b', 6])

tupel 元組
t.count(元素值)       表示這個元素出現的次數
t.index(元素值)       輸出其下標

print(l.index(6))
0

In [85]: ll = [1,2,3,4,5,1,1,2]
In [85]: ll = [1,2,3,4,5,1,1,2]
In [86]: print(ll.count(1))
3
In [87]: print(ll.count(2))
2
In [88]: print(ll.count(5))
1
In [89]: print(ll.count(7))
0

list 列表
自帶了一些功能:
l.
l.append   l.count    l.extend   l.index    l.insert   l.pop      l.remove   l.reverse  l.sort

l.append(元素值)   新增到現有列表的最後面
l.append([4,5,6])
l
['fenye', 25, (1, 2, 3), [4, 'b', 6], 6, [4, 5, 6]]

註釋:append() 可以給空列表增加,也可以給存在list的列表寫入:

l.count() 和 l.index()  同tuple的功能是一樣的:

l.insert(下標,列表名稱)
ll = []
In [32]: l2 = [0,9,5]
l.insert(2,ll)
1.insert(2,l2)
l
Out[41]: ['fenye', [0, 9, 5], [], 25, (1, 2, 3), [4, 'b', 6], 6, [4, 5, 6]]
註釋:新增後原來的列表,如 l1 和 l2 就不存在了:
然後在用append()增加內容:
l[2].append('python')
l[2].append('linux')
append() 給空列表插入內容:     //  不過一次只能傳入一個引數:
In [48]: l3 = []
In [53]: l3.append('linux')
In [54]: l3.append('python')
In [55]: l3
Out[55]: ['linux', 'python']

l.pop(下標)           // 根據下標來刪除的,會顯示在螢幕上:
l.pop(2)
Out[65]: (1, 2, 3)
In [66]: l
Out[66]: [['python', 'python', 'linux'], 25, [4, 'b', 6], 6]

l.remove(元素)         // 根據元素刪除,不會顯示在螢幕上:
l.remove(25)
In [69]: l
Out[69]: [['python', 'python', 'linux'], [4, 'b', 6], 6]

l.sort()        //排序

l.sort()
In [74]: l
Out[74]: [6, [4, 'b', 6], ['python', 'python', 'linux']]

l.reverse()         //反轉
l.reverse()
In [72]: l
Out[72]: [6, [4, 'b', 6], ['python', 'python', 'linux']]

多維列表:
線形的list
一維: 一行一列的list
a = [1,2,3,4,5]       // 一行五列也是一個多維list

multi_dim_a = [[1,2,3],
               [2,3,4],
               [3,4,5]]
               
如何輸出它的值呢?          // 行數和列數都是以0開始的。
print(multi_dim_a[0][1])    // 第一個方括號表示第幾行,第二個方括號表示第幾列;
In [101]: print(multi_dim_a[0][1])           第0行第一列      
2
In [102]: print(multi_dim_a[2][2])           第2行第二列
5
           

dictionary  字典     字典是無序的
在字典中,有key和 value兩種元素,每一個key對應一個value, key是名字, value是內容。
註釋:  字典是以 key:value 形式, 中間以冒號分割,  key 值是不可變的。
In [105]: dic = {}
In [106]: print(type(dic))
<type 'dict'>
定義一個字典:
dic = {'name':'fenye','age':25,(1,2,3):(4,5,6),(7,8):[9,8,7]}
In [109]: dic
Out[109]: {'age': 25, 'name': 'fenye', (1, 2, 3): (4, 5, 6), (7, 8): [9, 8, 7]}
list的key值不能用list,因為list的值是可變的:
dic字典取出key的兩個方法:
In [162]: dic['name']
Out[162]: 'fenye'
In [165]: print(dic['linux'])
python
dic.get('name')

新增新元素:
dic[key] = value
dic[b] = 20

dic.
dic.clear       dic.get         dic.iteritems   dic.keys        dic.setdefault  dic.viewitems
dic.copy        dic.has_key     dic.iterkeys    dic.pop         dic.update      dic.viewkeys
dic.fromkeys    dic.items       dic.itervalues  dic.popitem     dic.values      dic.viewvalues
dic.copy()
1、dic1 = dic.copy()
In [124]: dic1
Out[124]: {'age': 25, 'name': 'fenye', (1, 2, 3): (4, 5, 6), (7, 8): [9, 8, 7]}
2、dic.clear
In [134]: dic3.clear()
In [135]: dic3
Out[135]: {}
3、dic.get('key值')
In [138]: dic.get('name')
Out[138]: 'fenye'
4、dic.has_key('key值')
In [141]: dic.has_key(25)
Out[141]: False
In [142]: dic.has_key('age')
Out[142]: True
5、dic2.items()
Out[144]: [('age', 25), ((7, 8), [9, 8, 7]), ('name', 'fenye'), ((1, 2, 3), (4, 5, 6))]
6、In [146]: dic.keys()
Out[146]: ['age', (7, 8), 'name', (1, 2, 3)]
7、In [147]: dic.values()
Out[147]: [25, [9, 8, 7], 'fenye', (4, 5, 6)]
8、dic.pop('age')
Out[148]: 25
9、update()
In [156]: dic3
Out[156]: {'linux': 'python'}
In [157]: dic
Out[157]: {'name': 'fenye', (1, 2, 3): (4, 5, 6), (7, 8): [9, 8, 7]}
In [158]: dic.update(dic3)
In [159]: dic
Out[159]: {'linux': 'python', 'name': 'fenye', (1, 2, 3): (4, 5, 6), (7, 8): [9, 8, 7]}

可以用for來列印:
for k,v  in dic.items():
    print "%s:%s" % (k,v)
    
age:25
(7, 8):[9, 8, 7]
name:fenye
(1, 2, 3):(4, 5, 6)
    
dic4 = {(1,2,3):{1:2}}

註釋: 字典裡面還可以再把字典做為 value, 或者是fun() 也是可以的。

dic4 = {(1,2,3):{1:2}}

dic5 = {(1,2,3):fun()}

如果字典做為value,如何找字典的值: {'apple': [1, 2, 3], 'orange': 2, 'pear': {1: 3, 3: 'a'}} In [200]: print(d['pear']) {1: 3, 3: 'a'} In [201]