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 ...
随机推荐
- .NET跨平台之旅:将示例站点从 ASP.NET 5 RC1 升级至 ASP.NET Core 1.0
终于将“.NET跨平台之旅”的示例站点 about.cnblogs.com 从 ASP.NET 5 RC1 升级至 ASP.NET Core 1.0 ,经历了不少周折,在这篇博文中记录一下. 从 AS ...
- 抱歉!15:44-16:39阿里云RDS故障造成全站不能正常访问
非常非常抱歉!2016年3月7日15:44-16:39,由于阿里云RDS(云数据库)故障,造成全站不能正常访问,给您带来了很大很大的麻烦,恳请您的谅解! 故障是在15:44开始出现的,应用日志中出现大 ...
- c#连接关闭了,事务并没有关闭
用的是mysql引擎是InnoDB,用到了连接池. 连接还没关闭,但是事务开启,并执行了更新id=14的操作,这是把这一行锁住了,可以查询,但不能更新和删除,必需等锁释放,提交换回滚事务时锁被释放.直 ...
- Ubuntu 16.04 LAMP server 指南 - 配置 Apache2.4,PHP7,和MariaDB(而不是MySQL)
翻译自:https://www.howtoforge.com/tutorial/install-apache-with-php-and-mysql-on-ubuntu-16-04-lamp/ 昨天在虚 ...
- JavaScript模板引擎artTemplate.js——结语
再次首先感谢模板的作者大神,再次放出github的地址:artTemplate性能卓越的js模板引擎 然后感谢博客园的一位前辈,他写的handlebars.js模板引擎教程,对我提供了很大的帮助,也是 ...
- .Net4.0以上使用System.Data.Sqlite
最近对Sqlite感兴趣,就尝试了一下用c#连接,我用的版本是vs2013,默认开发环境是.net4.5,,按照网上的教材,下载了System.Data.Sqlite,然后写了下面这个简单的测试代码, ...
- mtk flash tool,Win7 On VirtualBox
SP_Flash_Tool_exe_Windows_v5.1624.00.000 Win7 在 VirtualBox, 安裝 mtk flash tool, v5.1628 在燒錄時會 fail. v ...
- 理解javascript里的ABC--apply bind call
一,三者共同点 js中的apply,call,bind是对于初学者比较难的概念之一,比如说我..参考几篇文章之后,统一来讲, 1.这三个函数都属于Function.prototype下面的方法,如下图 ...
- UIDynamic--动力元素行为:UIDynamicItemBehavior
属性分析: @property (nonatomic, readonly, copy) NSArray* items; @property (readwrite, nonatomic) CGFloat ...
- SVO原理解析
最近空闲时间在研究Semi-Direct Monocular Visual Odometry(SVO)[1,2],觉得它值得写一写.另外,SVO的运算量相对较小,我想在手机上尝试实现它. 关于SVO的 ...