1. 程式人生 > >【Python技術棧】02 Python3 Code 函式、類與繼承、裝飾器

【Python技術棧】02 Python3 Code 函式、類與繼承、裝飾器

0723 函式引數

*argm: 元組型別
**argm: 字典型別

In [1]: def sum(a, b, *argm):
   ...:     print(a, b, argm)
   ...: 
   ...: sum(1, 2, 'evan', 'pig', 'dog')
   ...: 
   ...: 
1 2 ('evan', 'pig', 'dog')

In [2]: #coding=utf-8
   ...: def sum2(a, b, **agrm):
   ...:     print(a, b, agrm)
   ...: 
   ...: sum2(
1, 2, i='evan', y='pig') ...: ...: 1 2 {'i': 'evan', 'y': 'pig'}

0723 函式

dict.keys(): 獲取字典中的鍵(key)的方法

#coding=utf-8

dict = {'admin':'123', 'yuyh':'yuhua', 'zhang':678}

def is_sucess_login(name, passwd):
	if name in dict.keys():
		if passwd == dict.get(name):
			return 'sucess'
		else
: return 'failure' else: return 'failure' name = input('請輸入你的使用者名稱:') passwd = input('請輸入你的密碼:') regiter = is_sucess_login(name, passwd) print(regiter)

0723 函式-檔案操作

前提:在相應的目錄(/home/hyh/test1)中新增使用者名稱。不新增則建立使用者。

#coding=utf-8

def file_write_findall(name):
	file = open('/home/hyh/test1', 'r'
) temp = 0 #count = 0 #list = [] for i in file.readlines(): i = i.strip('\n') b = i.split(' ') #list.extend(b) if name in b: temp = 1 if temp == 1: #print(list) file = open('/home/hyh/test1', 'r') #file.read() print('使用者名稱存在檔案中:') for j in file.readlines(): j = j.strip('\n') c = j.split(' ') print(c) if temp == 0: file = open('/home/hyh/test1', 'a') file.write('\n%s'%name) file.close() print('添加了新使用者:%s'%name) name = input('請輸入使用者名稱:') file_write_findall(name)

0723 全域性變數

global a 設定為全域性變數
這裡global a 之後設定a=10, 則函式test2()呼叫a時,a=10
註釋掉全域性設定,則函式test2()呼叫時,a還是100.

#coding=utf-8
a = 100
def test1():
#	global a
	a = 10
	print(a)
def test2():
	print(a)

test1()
test2()

0724 os模組

具有普遍作業系統功能
模組使用前一定要匯入
os.system(‘ls’) #執行系統中的命令
os.remove() #刪除系統中檔案
os.getcwd() #當前路徑
print(os.listdir(’/opt’)) #指定目錄下所有檔案和檔名
print(os.path.split(’/var/log/syslog’)) #返回一個路徑的目錄和檔名
print(os.path.isfile(’/var/log/syslog’)) #判斷是否是檔案
os.system(‘ifconfig’)
os.path.isdir() #判斷是否是目錄
os.path.exists() #判斷存在性

#coding=utf-8
import os

'''
1.鍵盤中輸入一個檔案路徑
2.判斷該路徑是否存在
        如果存在,判斷該路徑下是否存在log檔案
                如果存在檔案,打印出檔案內容
                如果不存在檔案,建立該檔案,並且提示檔案已經建立完畢
        如果不存在,在該路徑下建立該路徑,並且提示路徑建立完畢
'''

url = input('enter url:')
if os.path.exists(url):
	newfile = url + '/log'
	print(os.path.isfile(newfile))
	
	if os.path.isfile(newfile) == True:
		file = open(newfile,'r')
		for i in file.readlines():
			i = i.strip('\n')
			b = i.split('   ')
			print(b)
		'''for i in file:
			print(i)'''
		file.close()
	else:
		file = open(newfile,'w')
		file.close()
else:
	os.system('mkdir -P '+url) #級聯目錄需要加-P

0724 匿名函式

1、lambda a, b: a+b 實現a+b的運算
2、student.sort(key=lambda x: x[‘age’])實現在student列表中對裡面的字典元素按照key='age’排序

#coding=utf-8

#匿名函式簡單應用
def operation(a, b, opt):
	re = opt(a, b)
	return re

num1 = int(input('num1: '))
num2 = int(input('num2: '))

result = operation(num1, num2, lambda a,b:a+b)
print(result)

##匿名函式應用2: 列表中字典元素進行排序
student = [{'name':'tom','age':19},{'name':'jerry','age':20}]
student.sort(key=lambda x: x['age'])
print(student)

0725 字串過載

#coding=utf-8

class Number:
	def __init__(self, value):
		self.value = value
	def __repr__(self):
		return str(self.value)
	def __add__(self, other):
		return self.value + other
	def __radd__(self, other):
		return self.value + other

s = Number(101)
print(s)
print(s + 1)

執行結果:
101
102

0725 類的方法

@classmethod: 註解的方式註明為類的方法

#coding = utf-8

class people:
	country = 'china'
	@classmethod
	def getcountry(cls):
		return cls.country

p = people()
p.country = 'USB'
print(p.getcountry())
p.country = 'usa'
print(people.getcountry())

people.country = 'USA'
print(p.getcountry())

0725 繼承

子類可以繼承父類的方法,也可以重寫父類的方法。

#coding=utf-8

class baseuser:
	def findme(self):
		print('only find myself infomation.')


class manager(baseuser):
	def updateme(self):
		print('modify myself.')


class rootmaneger(manager):
	def findother(self):
		print('i can find other people information.')

	def updateother(self):
		print('i can modify others\' information')


xiaoming = rootmaneger()
xiaoming.updateme()
xiaoming.updateother()
xiaoming.findme()

執行結果:
modify myself.
i can modify others’ information
only find myself infomation.

0725 多繼承

class c(color_a, color_b):
即類c 同時繼承類color_a 和 類color_b,可以繼承這兩個類的方法。

#coding = utf-8
class color_a:
	def colora(self):
		return 'i am red.'

class color_b:
	def colorb(self):
		return 'i am pure.'

class c(color_a, color_b):
	def colorc(self):
		return 'i am c.'

democ = c()
s = democ.colorc()
b = democ.colora()
print(b)

0725 類的本身例項變數self

所謂的self,可以理解為自己
可以把self當做C++中類裡面的this指標一樣理解,就是物件自身的意思
某個物件呼叫其方法時,python直譯器會把這個物件作為第一個引數傳遞給self,所以開發者只需要傳遞後面的引數即可
和普通數相比,在類中定義函式只有一點不同,就是第一引數永遠是類的本身例項變數self,並且呼叫時,不用傳遞該引數

Python中self用法詳解
https://blog.csdn.net/CLHugh/article/details/75000104

#coding=utf-8
class student:
	def __init__(self, name):
		self.name = name
	def info(self):
		print('your name is %s' % self.name)

def studentinfo(student):
	student.info()

# heygor是student類的例項化
heygor = student('simida')

# 物件例項化後可以使用類中的方法
# studentinfo括號中的heygor是已經例項化的物件,可以呼叫類中的方法
# 注意:函式的傳參可以傳入常規引數也可以傳入物件
studentinfo(heygor)

執行結果:
your name is simida

0725 裝飾器

裝飾器簡單應用:實現一個計時器,監控程式執行的時間。

#coding = utf-8
import time


def deco(operation):
	def wrapper():
		starttime = time.time()
		operation()
		endtime = time.time()
		msecs = endtime - starttime
		print('time is %d s' % msecs)
	return wrapper

@deco
def operation():
	print('hello')
	time.sleep(2)
	print('world')

if __name__ == '__main__':
	f = operation
	operation()

執行結果:
hello
world
time is 2 s

0725 裝飾器函式

#coding = utf-8
import time

# 核心函式bar
def bar():
	time.sleep(2)
	print('plase wait for me!')


# 裝飾器函式
def deco(func):
	start_time = time.time()
	print('開始計時...')	
	func()
	print('計時結束...')
	endtime = time.time()
	sec = endtime - start_time
	print('該核心函式用時 %d 秒' % sec)
	return func


deco(bar)

執行結果:
開始計時…
plase wait for me!
計時結束…
該核心函式用時 2 秒

0725 裝飾器引數

def func(a, b): --> def deco(func): --> def splytime(a, b):
即在裝飾器中進行對引數的處理
可以應用在登入上,傳入使用者名稱和密碼,對其進行驗證,通過之後才能繼續操作

#coding = utf-8
import time

def deco(func):
	
	def splytime(a, b):
		starttime = time.time()
		func(a, b)
		endtime = time.time()
		esc = endtime - starttime
		print('esc = %d' % esc) 
	return splytime


@deco
def func(a, b):
	time.sleep(1)	
	print('a+b=',a+b)


f = func
f(12, 23)

執行結果:
a+b= 35
esc = 1

0725 裝飾器執行的順序

@deco
@deco2
def func():
這裡有兩個裝飾器@deco, @deco2
裝飾器其實是自頂向下的

Python 裝飾器執行順序迷思
https://www.cnblogs.com/nisen/p/6193426.html?utm_source=itdadao&utm_medium=referral

#coding = utf-8
import time

def deco(func):
	print('進入decO1裝飾器...')
	def wrapper():
		print('deco1')
		func()
		print('deco1 latter')
	return wrapper

def deco2(func):
	print('進入deco2裝飾器...')
	def wrapper():
		print('deco2')
		func()
		print('deco2 latter')
	return wrapper

@deco
@deco2
def func():
	print('func')

f = func
f()

執行結果:
進入deco2裝飾器…
進入decO1裝飾器…
deco1
deco2
func
deco2 latter
deco1 latter