您的位置:首页 > 其它

面向对象基础,封装,继承,多态

2016-11-21 17:25 666 查看

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("hei ren","22","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("hei ren","22","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!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: