python基础2-面向对象

面向对象介绍,专业名词:

特性

class
object

三大特性:封装、继承、多态

语法:属性、方法、构造函数、析构函数

私有方法,私有属性,

类变量,实例变量


最简单面向对象实例
class Dog:
    def __init__(self,name):
        self.name =name
    def bulk(self):
        print("%s: wang wang wang" % self.name)
d1 = Dog("tom1")
d2 = Dog("tom2")
d3 = Dog("tom3")

d1.bulk()
d2.bulk()
d3.bulk()

 

构造函数

class Role(object):
    n = 123  #类变量
    name = "我是类name"
    n_list = []  #如果类变量是list,那么各个实例与类的该变量就是共用一个内存地址
    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

    def shot(self):       #类的方法,功能  (动态属性)
        print("shooting...")

    def got_shot(self):
        print("ah...,I got shot...")

    def buy_gun(self,gun_name):
        print("%s just bought %s" %(self.name,gun_name))

print(Role)
print(Role.n)
r1 = Role('Alex','police','AK47') #实例化(初始化一个类,=造了一个对象)

#把一个类变成一个具体对象的过程叫实例化
r2 = Role('Jack','terrorist','B22')  #生成一个角色

r1.buy_gun("AK47")
print(r1.n,r1.name)
print(Role.name)

  

类变量与实例变量

class Person:
    cn = "中国"
    #类变量的用途:实例共用的属性,节省开销
    # 若cn="中国"定义在实例变量里,就是很多份内存,而在类变量中就是一份内存
    def __init__(self,name,age):
        self.name = name
        self.age = age

p1 = Person("jack",22)
print(p1.name,p1.age,p1.cn)

析构函数(方法)

#析构函数:在实例释放、销毁的时候自动执行的,通常用于做一些收尾工作,如关闭一些数据库连接,关闭打开的临时文件
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
    def __del__(self):
        print("%s 彻底死啦。。。" % self.name)
    #只要删除变量就会执行,或程序退出就会执行
    def shot(self):       #类的方法,功能  (动态属性)
        print("shooting...")
    def got_shot(self):
        print("ah...,I got shot...")
    def buy_gun(self,gun_name):
        print("%s just bought %s" %(self.name,gun_name))
r1 = Role('ATom','police','AK47') #实例化(初始化一个类,=造了一个对象)
del r1
#把一个类变成一个具体对象的过程叫实例化
r2 = Role('Jack','terrorist','B22')  #生成一个角色
r2.buy_gun("ak")

私有方法、私有属性

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
    def show_status(self):
        print("name:%s ,life_value:%s" %(self.name,
                                         self.__life_value))
    def shot(self):       #类的方法,功能  (动态属性)
        print("shooting...")
    def __got_shot(self):
        #前面加__就变成私有方法
        print("ah...,I got shot...")
    def buy_gun(self,gun_name):
        print("%s just bought %s" %(self.name,gun_name))
r1 = Role('ATom','police','AK47')
r2 = Role('Jack','terrorist','B22')
r1.show_status()

输出:
name:ATom ,life_value:100

 

继承(其中就涉及到:新式类,经典类,因为新式类与经典类主要体现在继承上)

 

单继承实例

class People(object):    #新式类
#class People():      #经典类
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def eat(self):
        print("%s is eating ..." % self.name)
    def talk(self):
        print("%s is talking ..." % self.name)
    def sleep(self):
        print("%s is sleeping..." % self.name)
class Man(People):
    def __init__(self,name,age,money):
        super(Man,self).__init__(name,age)     #新式类
        #People.__init__(self,name,age)      #经典类
        self.money = money
        print("%s 一出生就有money  %s" % (self.name,self.money))
    def chou(self):
        print("%s is chouing ...... 20s ...done." % self.name)
    def sleep(self):
        People.sleep(self)
        print("man is sleeping")
    #在调用父类的方法,同时添加自己的新功能

class Woman(People):
    def get_birth(self):
        print("%s is born a baby..." % self.name)
m1 =Man("tom",22,2000)

m1.eat()
m1.sleep()

w1 = Woman("Lily",23)
w1.get_birth()


#返回

tom 一出生就有money  2000
tom is eating ...
tom is sleeping...
man is sleeping
Lily is born a baby...

 

多继承实例

class People(object):    #新式类
#class People():      #经典类
    def __init__(self,name,age):
        self.name = name
        self.age = age
        self.friends = []     #flag1
    def eat(self):
        print("%s is eating ..." % self.name)
    def talk(self):
        print("%s is talking ..." % self.name)
    def sleep(self):
        print("%s is sleeping..." % self.name)
class Relation(object):
    def make_friends(self,obj):
        print("%s is making friends with %s " %(self.name,obj.name))
        self.friends.append(obj)       #flag2
class Man(People,Relation):
    def __init__(self,name,age,money):
        super(Man,self).__init__(name,age)     #新式类
        #People.__init__(self,name,age)      #经典类
        self.money = money
        print("%s 一出生就有money  %s" % (self.name,self.money))
    def chou(self):
        print("%s is chouing ...... 20s ...done." % self.name)
    def sleep(self):
        People.sleep(self)
        print("man is sleeping")
    #在调用父类的方法,同时添加自己的新功能

class Woman(People,Relation):
    def get_birth(self):
        print("%s is born a baby..." % self.name)


m1 =Man("tom",22,2000)
w1 = Woman("Lily",23)

m1.make_friends(w1)
print(m1.friends[0].name)    #flag3

 返回:

tom 一出生就有money  2000
tom is making friends with Lily 
Lily

  

注:前面有三行注释:标记为flag1/2/3

 

强行拉出obj内存,为的是方便理解为何relation父类中make_friends方法为何传入的参数是obj,而非obj.name,(因为obj.name是字符串,不能够适应变化)

 

继承的优先级

class A():
    def __init__(self):
        print("A")
class B(A):
    # pass
    def __init__(self):
        print("B")
class C(A):
    # pass
    def __init__(self):
        print("C")

class D(B,C):
    pass
    # def __init__(self):
    #    print("D")

obj = D()
# 在python3中经典类和新式类统一都是广度优先,
顺序D>B>C>A ,先横向,再纵向,这叫:广度优先,
# 在python2中经典类是深度优先,顺序D>B>A>C
       新式类是广度优先 

 

  

继承实例
四个类(学校,学校成员,老师,学生)
class School(object):
    def __init__(self,name,addr):
        self.name = name
        self.addr = addr
        self.students = []
        self.staffs = []
    def enroll(self,stu_obj):
        print("为学员 %s 办理注册手续" % (stu_obj.name))
        self.students.append(stu_obj)
    def hire(self,staff_obj):
        print("雇佣新员工%s " % (staff_obj.name))
        self.staffs.append(staff_obj)
class Schoolmember(object):
    def __init__(self,name,age):
        self.name = name
        self.age = age
    def tell(self):
        pass
class Teacher(Schoolmember):
    def __init__(self,name,age,course,salary):
        super(Teacher,self).__init__(name,age)
        self.course = course
        self.salary = salary
    def teach(self):
        print("Teacher [%s] is teaching [%s] course" % (self.name,self.course))
    def tell(self):
        print(''' "info of %s "
              "name :   %s"
              "age :    %s"
              "course : %s"
              "salary : %s" ''' %(self.name,self.name,self.age,self.course,self.salary) )
class Student(Schoolmember):
    def __init__(self,name,age,grade,sid):
        super(Student,self).__init__(name,age)
        self.grade = grade
        self.sid = sid

    def tell(self):
        print(''' "info of %s"
              "name :   %s"
              "age :    %s"
              "grade :  %s"
              "sid :    %s"  ''' %(self.name,self.name,self.age,self.grade,self.sid) )
    def pay_tuition(self,amount):
        print("%s has paid tution for $ %s" % (self.name,amount))

school = School("老男孩","沙河")
t1 = Teacher("bailaoshi",40,"pyhical",5000)
t2 = Teacher("heilaoshi",30,"PythonDevOps",40000)

s1 = Student("xiaobai",20,1709,1000001)
s2 = Student("qiushui",26,1709,1000002)

t1.tell()
s1.tell()

school.enroll(s1)
school.enroll(s2)
school.hire(t1)

print(school.students)
print(school.staffs)

for stu in school.students:
    stu.pay_tuition(5000)

返回:

 "info of bailaoshi "
              "name :   bailaoshi"
              "age :    40"
              "course : pyhical"
              "salary : 5000" 
 "info of xiaobai"
              "name :   xiaobai"
              "age :    20"
              "grade :  1709"
              "sid :    1000001"  
为学员 xiaobai 办理注册手续
为学员 qiushui 办理注册手续
雇佣新员工bailaoshi 
[<__main__.Student object at 0x0000000000AA0F28>, <__main__.Student object at 0x0000000000AA0F60>]
[<__main__.Teacher object at 0x0000000000AA0EB8>]
xiaobai has paid tution for $ 5000
qiushui has paid tution for $ 5000


多态:一个接口,多种实现

class Animal(object):
    def __init__(self,name):
        self.name = name
    @staticmethod
    def animal_talk(obj):
        obj.talk()

class Cat(Animal):
    def talk(self):
        print("%s: 喵喵喵!" % self.name)

class Dog(Animal):
    def talk(self):
        print("%s: 旺旺旺!" % self.name)
c1 = Cat("tom")
d1 = Dog("泰迪")

# def func(obj):
#     obj.talk()
# c1.talk()
# d1.talk()
# func(d1)
# func(c1)

Animal.animal_talk(c1)
Animal.animal_talk(d1)

返回:

tom: 喵喵喵!
泰迪: 旺旺旺!

 






posted @ 2017-09-26 12:06  larlly  阅读(126)  评论(0)    收藏  举报