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 ...
随机推荐
- textarea 中的 innerHTML 和 value
<textarea></textarea> <input type="button" value="click" /> &l ...
- Binding笔记
Binding基础 绑定某个对象的属性值到控制上,写法如下: public class Order : INotifyPropertyChanged//只要实现此接口 { public event ...
- 日货EmEditor的使用小技巧
1.查看->大纲向导,可层级显示HTML 2.工具->插件->资源管理器,可在左侧显示资源管理器 3.工具->插件->单词自动完成,可实现单词智能提示功能
- PRINCE2特征(二)
英国体系环境下项目有什么特征(二) 今天又要和大家分享了,这个时间也是自己很喜欢的时刻.上次给大家分享的是英国体系下项目的特征之一:临时性.不知道大家还有没有印象,英国体系下项目的特征有五个,今天来给 ...
- sql 取汉字首字母
)) ) --用于加密 --WITH ENCRYPTION as begin declare @intLen int ) ) set @intLen = len(@str) set @strRet = ...
- Servlet-Cookie源码分析 源码环境:Tomcat8
最近在学习servlet的一些实现细节,阅读了Cookie的源码. Cookie本质上是服务器发送给客户端(主要是浏览器)的一个会话临时数据. 其源码注释文档的说明: Creates a cookie ...
- WPF学习系列 绘制旋转的立方体
我是一年经验的web程序员,想学习一下wpf,比较喜欢做项目来学习,所以在网上找了一些项目,分析代码,尽量能够做到自己重新敲出来 第一个项目是 中间的方块会不停的旋转. 第一步,新建wpf项目 第二步 ...
- Unity Game窗口中还原Scene窗口摄像机操作 强化版
之前写的那个版本看来真的是不行啊.最近研究了一下官方第一人称脚本,人家的平滑过渡真的是没得说.借鉴了一下,写出来了一个新的比较完美的控制. 之前我们的操作是通过鼠标输入的开始坐标和转动坐标.其实官方有 ...
- Java开发环境搭建——Tomcat配置
指定tomcat的JDK版本可能由于种种原因,系统的JAVA_HOME配置的JDK版本并不是当前需要的版本,而tomcat默认使用的是JAVA_HOME的JDK.可以通过修改tomcat/bin/ca ...
- c#.net单例模式的学习记录!
一. 单例(Singleton)模式 单例模式的特点: 单例类只能有一个实例. 单例类必须自己创建自己的唯一实例. 单例类必须给所有其它对象提供这一实例. 单例模式应用: 每台计算机可以有若干个打印机 ...