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] Convert Sorted List to Binary Search Tree 将有序链表转为二叉搜索树
Given a singly linked list where elements are sorted in ascending order, convert it to a height bala ...
- 反序列化漏洞问题研究之php篇
php的反序列化反序列化漏洞又称php对象注入(php Object Injection)产生的问题主要分以下两类: 将传来的序列化数据直接unserilize,造成魔幻函数的执行.这种情况在一般的应 ...
- 关于我-dinphy简介
别 名:孜_行 英文名:dinphy QQ交流群:588266650 兴趣爱好:听音乐.打篮球.热衷于诗词文学 专 业:计算机 了 解:windows及Linux.android的基本 ...
- [bzoj3626][LNOI2014]LCA
Description 给出一个$n$个节点的有根树(编号为$0$到$n-1$,根节点为$0$). 一个点的深度定义为这个节点到根的距离$+1$. 设$dep[i]$表示点$i$的深度,$lca(i, ...
- 架构师养成记--14.重入锁ReentrantLock 和 读写锁 ReentrantReadWriteLock
ReentrantLock 有嗅探锁定和多路分支等功能,其实就是synchronized,wait,notify的升级. this锁定当前对象不方便,于是就有了用new Object()来作为锁的解决 ...
- BZOJ-2561-最小生成树 题解(最小割)
2561: 最小生成树(题解) Time Limit: 10 Sec Memory Limit: 128 MBSubmit: 1628 Solved: 786 传送门:http://www.lyd ...
- 将上传图片转成base64(转)
效果如下: <!DOCTYPE html> <html> <head> <meta charset="utf-8"><titl ...
- LVM逻辑卷管理命令
显示分区信息: [root@localhost /]# fdisk -l PV:物理硬盘格式化为物理卷(PV): [root@localhost /]# pvcreate /dev/sdb /dev/ ...
- AnjularJS系列6 —— 过滤器
第六篇,过滤器 AngularJS 过滤器可用于转换数据: 过滤器 描述 currency 格式化数字为货币格式. filter 从数组项中选择一个子集. lowercase 格式化字符串为小写. o ...
- C内嵌汇编-格式
C内嵌汇编-格式: __asm__(汇编语句部分:输出部分:输入部分破坏描述部分);C内嵌汇编以关键字"__asm__"或"asm"开始, 下辖四个部分, 各部 ...