面向对象进阶

来源:互联网 发布:淘宝卖家怎么认证 编辑:程序博客网 时间:2024/06/06 06:45

python面向对象

思维导图:
这里写图片描述

分类:

  • 面向过程编程:初学者容易接受,从上往下依次执行;
  • 面向函数编程:将某功能的代码封装为一个函数,使用时仅调用函数;
    (2+3)*2-1 jian(multi(add(2,3),2),1)

  • 面向对象编程:对函数进行分类和封装….

class people:               # 经典类class People(object):       # 新式类,object类是所有类的基类/父类    def __init__(self,name,age):    # 构造函数,当实例化对象时自动调用;        self.name = name            # 属性        self.age = age    def run(self):                  # 方法        print "running...."    def __del__(self):        print "deleteing......"     # 析构函数,删除实例化对象时自动调用;class Student(People):              # Student是子类,继承People这个父类;    passp1 = People("张策",18)p1.run()

面向对象的三个特性

封装

封装:把内容统一放在一个地方,看成一个整体,(实例化对象self和类的属性绑定在一起);
- 访问封装内容的两种方式:
通过self去访问封装的内容;(self.name)
通过实例化的对象名去访问封装的内容;(p1 = People(“westos”,17) p1.age)

继承

继承:子承父业
- 新名词:基类/派生类, 父类/子类, 新式类和经典类
- 多继承:
新式类: 广度优先继承;(python2.x和python3.x均支持)
经典类:深度优先继承;(python2.x支持,python3.x没有经典类)
- 注意:
类的方法中可以传递一个对象;

class People(object):       # 新式类,object类是所有类的基类/父类    def __init__(self,name,age):    # 构造函数,当实例化对象时自动调用;        self.name = name            # 属性        self.age = age        print "%s is create...." %(self.name)    def run(self):                  # 方法        print "%s running...." %(self.name)    def __del__(self):        print "deleteing......"     # 析构函数,删除实例化对象时自动调用;class Relation(object):    **def make_relation(self,obj):** #传入一个对象作为参数        print "%s is related with %s" %(self.name,obj.name)class Student(People,Relation):              # Student是子类,继承People这个父类;      def __init__(self,name, age, sid):        # People.__init__(self,name,age)            # 如果父类名更改,此处也需要更改;        super(Student, self).__init__(name,age)     # 更推荐使用        self.sid = sidclass Teacher(People,Relation):    def __init__(self, name, age, tid):        #People.__init__(self,name,age)                  super(Teacher, self).__init__(name, age)         self.tid = tids1 = Student("lijian", 18, "007")t1 = Teacher("westos", 18, "001")s1.make_relation(t1)

多态

如果子类调用的方法,子类没有,父类有,运行父类;如果子类调用的方法,子类有,父类也有,只运行子类的;

面向对象进阶

  • 类变量,全局变量,在内存中只存储一份;
  • 普通的对象属性,每个对象中都需要存储一份;
class People(object):    # def __init__(self,name,age,country="china"):  #每创建一个实例就会在内存中重新存储一次    #     self.name=name    #     self.age=age    #     self.country=country    country="China"      #全局变量,类的属性,只需要存储一次    def __init__(self,name,age):        self.name=name        self.age=age    def run(self):        print "%s is running..."%self.namep1=People("mj",18)print p1.name ,p1.age,p1.countryprint id(People.country),id(p1.country)

方法

  • 实例化方法:第一个参数为self(实例化本身);
  • 类方法:第一个参数是cls(类本身);通过@classmethod装饰器实现;
  • 静态方法:第一个参数既不是self也不是cls;通过@staticmethod方法实现;
class DateTest(object):    def __init__(self,year,month,day):        self.year=year        self.month=month        self.day=day    def show_date(self):        return "Year:{}\nMonth:{}\nDay:{}".format(self.year,self.month,self.day)    #类方法    @classmethod    def get_str_date(cls,s):        if cls.is_date_vaild(s):            year,month,day=map(int,s.split("-"))            date1=cls(year,month,day)  #实例化date1            return date1        #print cls        #print date1, type(date1),id(date1)        return None    #静态方法    @staticmethod    def is_date_vaild(s):        year, month, day = map(int, s.split("-"))        return year>=1970 and 0<month<=12 and 0<day<=31d=DateTest.get_str_date("2017-09-05") #赋值print d.show_date()d1=DateTest.get_str_date("2017-09-05")if d1:    print d1.show_date()else:    print "error date!"

特殊属性

装饰器property

  • 经典类
class Pager:    def __init__(self,request_page):        self.request_page=request_page        self.per_items=10    @property    def start(self):        val=(self.request_page-1)*self.per_items        return val    @property    def end(self):        val =self.request_page*self.per_items        return valp=Pager(2)print p.startprint p.end
  • 新式类
class Goods(object):     def __init__(self):         self.old_price = 100         self.discount = 0.7     @property     def price(self):         new_price = self.old_price * self.discount         return new_price     @price.setter     def price(self, value):         self.old_price = value     @price.deleter     def price(self):         del self.old_priceg = Goods()print g.priceg.price = 200 #通过@price.setter实现print  g.pricedel g.price #通过@price.deleter实现print g.price  #报错
class Goods(object):    def __init__(self):        self.old_price=100        self.discount=0.7    def get_price(self):        new_price=self.old_price*self.discount        return new_price    def set_price(self,value):        self.old_price=value    def del_price(self):        del self.old_price        return None    price=property(get_price,set_price,del_price)g=Goods()print g.priceg.price=200print g.pricedel g.priceprint g.price #报错

类的特殊成员

私有成员

class People(object):    def __init__(self,name,age):        self.name = name        self.__age = age    # _People__age == self.__age    def get_age(self):        print  self.__agep = People("fentiao",10)p.__age = 20  print p.__age  #20,生成新变量p.get_age() #10,对象p的age属性print p._People__age #10,同上
原创粉丝点击