【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()

# evan是student类的实例化
evan = student('Evan')

# 对象实例化后可以使用类中的方法
# studentinfo括号中的evan是已经实例化的对象,可以调用类中的方法
# 注意:函数的传参可以传入常规参数也可以传入对象
studentinfo(evan)

运行结果:
your name is Evan

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

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值