python基础七
subprocess
subprocess是专门用来替代os.system;os.spawn更加的先进。
但是subprocess.run()是在python3.5之后才出现的
实例
>>> subprocess.run(["df",'-h'])
以上代码运行结果
Filesystem Size Used Avail Use% Mounted on /dev/vda3 91G 2.3G 84G 3% / tmpfs 3.9G 0 3.9G 0% /dev/shm /dev/vda1 194M 65M 120M 35% /boot CompletedProcess(args=['df', '-h'], returncode=0)
接收字符串格式命令,返回元组形式,第1个元素是执行状态,第2个是命令结果
实例一
>>> subprocess.getstatusoutput("ls /application/tools")
以上代码运行结果
(0, 'Python-3.5.2\nPython-3.5.2.tgz')
实例二
>>> print((subprocess.getstatusoutput("ls /application/tools/")[1]))
以上代码运行结果
Python-3.5.2 Python-3.5.2.tgz
subprocess.Popen既可以打印正确输出stdout,也可以打印错误输出stderr。
>>> res=subprocess.Popen("ifconfig|grep 10.0",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) >>> res.stdout.read()
以上代码运行结果
>>> res.stdout.read() b' inet addr:10.0.1.14 Bcast:10.0.1.255 Mask:255.255.255.0\n collisions:0 txqueuelen:1000 \n collisions:0 txqueuelen:1000 \n'
对于要等待的命令
>>> res=subprocess.Popen("sleep 10;echo 'hello'",shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
当上面的命令执行完了之后, res.poll()的执行结果为0,res.wait()的执行结果为0,res.terminate()用来中断正在执行的命令。
面向对象
面向对象 object oriented programing
类的特性
封装
1.防止数据被随意修改
2.使外部程序不需要关注对象内部的构造,只需要通过此对象
对外提供的接口进行直接访问即可
继承
通过父类-》子类的方式以最小代码量的方式实现 不同角色的共同点和不同点的同时存在
类---》实例化--》实例对象
__init__构造函数
self.name = name # 属性, 成员变量,字段
def sayhi()# 方法, 动态属性
class Dog(object): def __init__(self,name): self.name=name def sayhi(self): print("hello ,I am a dog. My name is %s"%self.name) # Dog().sayhi() d=Dog("wangcai") d.sayhi()
以上代码运行结果
hello ,I am a dog. My name is wangcai
私有属性
__private_attr_name = value
def get_heart(self): #对外部提供只读访问接口
return self.__heart
r1._Role__heart 强制访问私有属性
class Role(object): def __init__(self, name, role, weapon, life_value=100, money=15000): self.name = name self.role = role self.weapon = weapon self.life_value = life_value self.money = money self.__heart = "Normal" def status(self): print("%s is %s and have %s"%(self.name,self.role,self.weapon)) def shot(self): print("%s is shooting..." % self.name) def got_shot(self): print("ah...,I got shot...") self.__heart ="Die" print(self.__heart) def get_heart(self): return self.__heart def buy_gun(self, gun_name): print("%s just bought %s" % (self.name,gun_name) ) self.weapon = gun_name r1 = Role('HaiTao', 'police', 'AK47') #生成一个角色 r2 = Role('Jack', 'terrorist','B22') #生成一个角色 print(r1.name) print(r1.get_heart()) r1.got_shot() print(r1._Role__heart) #强制访问私有属性
以上代码运行结果
HaiTao Normal ah...,I got shot... Die Die
公有属性
nationality = "JP" 在类里直接定义的属性即是公有属性
class Role(object): nationality = "JP" def __init__(self, name, role, weapon, life_value=100, money=15000): self.name = name self.role = role self.weapon = weapon self.life_value = life_value self.money = money self.__heart = "Normal" def shot(self): print("%s is shooting..." % self.name) def got_shot(self): print("ah...,I got shot...") self.__heart ="Die" # def __del__(self): # print("del.....run...") r1 = Role("HaiTao", "警察","B22") r2 = Role("LiChuang", "警犬","B13") print(r1.nationality) print(r2.nationality) Role.nationality = "US" #更改类的公有属性 print(r1.nationality,r2.nationality) r1.nationality = "CN" print("after change...") print(r1.nationality) print(r2.nationality)
以上代码运行结果
JP JP US US after change... CN US
私有函数
class Role(object): nationality = "JP" def __init__(self, name, role, weapon, life_value=100, money=15000): self.name = name self.role = role self.weapon = weapon self.life_value = life_value self.money = money self.__heart = "Normal" def shot(self): print("%s is shooting..." % self.name) def got_shot(self): print("ah...,I got shot...") self.__heart ="Die" # def __del__(self): # print("del.....run...") r1 = Role("HaiTao", "警察","B22") r2 = Role("LiChuang", "警犬","B13") def shot2(self): print("run my own shot method", self.name ) r1.shot = shot2 r1.shot(r1) r2.shot()
以上代码运行结果
run my own shot method HaiTao LiChuang is shooting...
析构方法__del__
用于在实例被python的回收机制销毁时关闭实例打开的临时文件
class Role(object): nationality = "JP" def __init__(self, name, role, weapon, life_value=100, money=15000): self.name = name self.role = role self.weapon = weapon self.life_value = life_value self.money = money self.__heart = "Normal" def shot(self): print("%s is shooting..." % self.name) def got_shot(self): print("ah...,I got shot...") self.__heart ="Die" def __del__(self): print("del.....run...") r1 = Role("HaiTao", "警察","B22")
以上代码运行结果
del.....run...
继承
子类有就用子类,子类没有继承父类
class Person(object): def talk(self): print("person is talking...") class BlackPerson(Person): def talk(self): print("black person is blaba....") def walk(self): print("is walking") b=BlackPerson() b.talk() b.walk()
以上代码执行结果
black person is blaba.... is walking
先继承,再重构
class Person(object): def __init__(self,name,age): self.name=name self.age=age self.sex="normal" def talk(self): print("person is talking...") class WhitePerson(Person): pass class BlackPerson(Person): def __init__(self,name,age,strength): #先覆盖 Person.__init__(self,name,age) #再继承 self.strength=strength #再添加自己的东西 print(self.name,self.age,self.sex,self.strength) def talk(self): print("black person is blaba....") def walk(self): print("is walking") b=BlackPerson(","strong")
class Person(object): def __init__(self,name,age): self.name=name self.age=age self.sex="normal" def talk(self): print("person is talking...") class WhitePerson(Person): pass class BlackPerson(Person): def __init__(self,name,age,strength): #先覆盖 super(BlackPerson,self).__init__(name,age)#再继承(新式类) #Person.__init__(self,name,age) #再继承(旧式类) self.strength=strength #再添加自己的东西 print(self.name,self.age,self.sex,self.strength) def talk(self): print("black person is blaba....") def walk(self): print("is walking") b=BlackPerson(","strong")
class SchoolMember(object): '''学校成员基类''' member = 0 def __init__(self,name,age,sex): self.name = name self.age = age self.sex = sex self.enroll() def enroll(self): '''注册''' print("just enrolled a new school member [%s]"% self.name) SchoolMember.member +=1 def tell(self): print("------info:%s-----"%self.name) for k,v in self.__dict__.items(): print("\t",k,v) print("------end-----") def __del__(self): print("开除了[%s]..."% self.name ) SchoolMember.member -=1 class School(object): '''学校类''' def open_branch(self,addr): print("openning a new branch in ",addr) class Teacher(SchoolMember,School): '''讲师类''' def __init__(self,name,age,sex,salary,course): #SchoolMember.__init__(self,name,age,sex) #经典类写法 super(Teacher,self).__init__(name,age,sex) #新式类写法 self.salary = salary self.course = course # def tell(self): # print("""--------info:%s # name:%s # age:%s # salary :%s # """ % (self.name,self.name,self.age,self.salary)) def teaching(self): print("Teacher [%s] is teaching [%s]" % (self.name,self.course)) class Student(SchoolMember): def __init__(self,name,age,sex,course,tuition): SchoolMember.__init__(self,name,age,sex) self.course = course self.tuition = tuition #fee self.amount = 0 def pay_tuition(self,amount): print("student [%s] has just paied [%s]" %(self.name,amount)) self.amount += amount t1 = Teacher("Wusir", 28, "F*M",3000,"Python" ) s1 = Student("HaiTao", 38,"N/A","PYS15", 300000 ) s2 = Student("LIChuang",12,"M","PYS15", 11000 ) print(SchoolMember.member) t1.tell() t1.open_branch("SH") s2.tell() del s2 print(SchoolMember.member)
以上代码运行结果
just enrolled a new school member [Wusir] just enrolled a new school member [HaiTao] just enrolled a new school member [LIChuang] 3 ------info:Wusir----- sex F*M age 28 name Wusir salary 3000 course Python ------end----- openning a new branch in SH ------info:LIChuang----- sex M amount 0 age 12 name LIChuang tuition 11000 course PYS15 ------end----- 开除了[LIChuang]... 2 开除了[Wusir]... 开除了[HaiTao]...
经典类VS新式类
class A(object): # pass def __init__(self): self.n = "A" class B(A): # pass def __init__(self): self.n = "B" class C(A): # pass def __init__(self): self.n = "C" class D(B,C): pass # def __init__(self): # self.n = "D" d = D() print(d.n)
以上代码运行结果
B
多态
允许将子类类型的指针赋值给父类类型的指针。
class Animal: def __init__(self, name): # Constructor of the class self.name = name def talk(self): # Abstract method, defined by convention only raise NotImplementedError("Subclass must implement abstract method") class Cat(Animal): def talk(self): return 'Meow!' class Dog(Animal): def talk(self): return 'Woof! Woof!' d = Dog("d1") c = Cat("C1") # Animal.talk(d) # Animal.talk(c) def animal_talk(obj): print(obj.talk()) animal_talk(d) animal_talk(c)
以上代码运行结果
Woof! Woof! Meow!
python基础七的更多相关文章
- python基础(七)函数
作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢! 函数最重要的目的是方便我们重复使用相同的一段程序. 将一些操作隶属于一个函数,以后 ...
- 【笔记】Python基础七:正则表达式re模块
一,介绍 正则表达式(RE)是一种小型的,高度专业化的编程语言,在python中它内嵌在python中,并通过re模块实现.正则表达式模式被编译成一系列的字节码,然后由C编写的匹配引擎执行. 字符匹配 ...
- Python基础(七) python自带的三个装饰器
说到装饰器,就不得不说python自带的三个装饰器: 1.@property 将某函数,做为属性使用 @property 修饰,就是将方法,变成一个属性来使用. class A(): @prope ...
- python基础七--集合
12.221.昨日内容回顾 小数据池: int:-5--256 str:1.不能有特殊字符 2.*int不能超过20 编码:所能看到的最小构成单位叫字符 ascii : 8位 1字节 表示1个字符 u ...
- python 基础(七) 异常处理
异常处理 一.需求 当遇到错误的时候 不让程序停止执行 而是越过错误继续执行 二.主体结构 (抓取所有异常) try: 可能出现异常的代码段 except: 出现异常以后的处理 三.处理特 ...
- Python基础(七) 闭包与装饰器
闭包的定义 闭包是嵌套在函数中的函数. 闭包必须是内层函数对外层函数的变量(非全局变量)的引用. 闭包格式: def func(): lst=[] def inner(a): lst.append(a ...
- python基础七之copy
浅拷贝 没有嵌套,则copy后完全不同,有嵌套,则copy后本体不同,嵌套相同. l1 = [1, 2, [4, 5, 6], 3] l2 = l1.copy() print(l1 is l2) # ...
- python基础七之集合
集合:可变的数据类型,他里面的元素必须是不可变的数据类型,无序,不重复. 增加 set1 = {'zxc', 'zxf'} set1.add('zxv') # 无序添加 set1.update('zx ...
- 七. Python基础(7)--文件的读写
七. Python基础(7)--文件的读写 1 ● 文件读取的知识补充 f = open('file', encoding = 'utf-8') content1 = f.read() content ...
随机推荐
- [LeetCode] Unique Paths II 不同的路径之二
Follow up for "Unique Paths": Now consider if some obstacles are added to the grids. How m ...
- 编写轻量ajax组件01-对比webform平台上的各种实现方式
前言 Asp.net WebForm 和 Asp.net MVC(简称MVC) 都是基于Asp.net的web开发框架,两者有很大的区别,其中一个就是MVC更加注重http本质,而WebForm试图屏 ...
- 资源描述结构(Resource Description Framework,RDF)
资源描述框架(Resource Description Framework),一种用于描述Web资源的标记语言.RDF是一个处理元数据的XML(标准通用标记语言的子集)应用,所谓元数据,就是" ...
- call和apply的区别
call和apply都属于function prototype的一个方法. 定义:调用一个方法的对象,以另一个对象替换当前对象. 相同点:两个方法产生的作用是一样的. 不同点:方法传递的参数不同. c ...
- windows server 2008 各版本号下载地址(微软官网)
前言: 微软官网上下载系统的镜像文件要远比百度网盘下载起来得更快. Windows Server 2008 32-bit Standard(标准版)
- mysql在空闲8小时之后会断开连接(默认情况)
调试程序的过程发现,在mysql连接空闲一定时间(默认8小时)之后会断开连接,需要重新连接,也引发我对重连机制的思考.
- div内容溢出时显示滚动条
在style中添加overflow:scroll属性即可.
- nodejs异步处理
采用Async.Q.Promise等第三方库处理异步回调 Async 安装 npm install async --save-dev
- 父子页面之间元素相互操作(iframe子页面)
js/jquery获取iframe子页面中元素的方法: 一.使用window.frames["iframe的ID"]获取元素 window.onload = function() ...
- JS 的实例和对象的区别
对于传统的OOP思想,JS的语法确实比较难搞,其中之一就是实例和对象的区别. 什么是实例? 实例是类的具体化产品. JS语法没有类这个概念(当然ES6引用了类这个概念).只能通过构造函数来创建类,例如 ...