zoukankan      html  css  js  c++  java
  • python学习笔记(十九)-- 面向对象

    类:
    一个种类,一个模版,一个图纸。
    对象(也叫实例):
    根据类(模版)造出来的具体的东西。
    实例化:
    把类变成对象的过程
    构造函数:
    在这个类初始化(实例化)的时候执行的
    析构函数:
    在这个实例被销毁的时候自动执行
    self:
    本类对象,self就是实例,就是对象
    继承
    就是继承父类有的功能,可以直接使用父类功能
    类变量
    直接在类里面定义的变量就是类变量,实例也可以使用
    实例变量
    self.xxx 这种都是实例变量,不实例化不能使用
    类方法
    不需要实例化就能调用的方法,可以使用类变量,但不能调用类里面的方法
    用@classmethod装饰
    什么时候使用:如果这个方法是和类相关,但不需要使用实例变量,那就应该把这个方法定义成类方法
    静态方法
    和这个类没关系,不能调用类方法,不能使用类变量
    只是定义在这个类里面的一个普通的方法。
    如果这个方法,不需要使用类方法、类变量、实例方法、实例变量
    属性方法
    看起来像变量的一个方法
    封装
    多个功能写到一个类里
    私有
    只能在类里面调用的方法或者变量,类外面不能调用
    # class Person(object):#新式类定义,新的写法,效果一样
    #类名习惯大写
    class Person:#经典类定义
        country = '中国'#类变量,公用的,存在类里,不存在实例里
        def __init__(self,mouth,eyes,name):#构造函数,实例化时会自动调用执行
            print('self的内存地址: ', id(self))
            self.mouth = mouth #实例变量
            self.eyes = eyes
            self.name = name
        def fly(self):
            print('【%s】会飞'%self.name)
        def eat(self):
            print('【%s】会吃'%self.name)
        def say(self):
            print('【%s】,【%s】张嘴,【%s】只眼睛'%(self.name,self.mouth,self.eyes))
            print('%s的国际是%s'%(self.name,self.country))
        def smile(self):
            print('【%s】会笑'%self.name)
    
    nn = Person(1,2,'nana')#实例化,必须带上参数
    print('nn的内存地址: ',id(nn))
    #self的内存地址与对象的内存地址一样,self就是对象本身
    
    nn.smile()#调用方法
    nn.fly()
    nn.eat()
    nn.say()
    
    #函数传入一个实例
    def my_def(self):
        print(self.name)
        self.fly()
    my_def(nn)

    构造函数和析构函数

    class Car:
        def __init__(self,color,wheel=4):#构造函数,实例被创建的时候执行
            self.color = color
            self.wheel = wheel
            print('实例被创建的时候会自动执行我')
        def __del__(self):#析构函数,实例被销毁的时候执行
            print('实例被销毁的时候会自动执行我')
        def run(self):
            print('汽车在跑')
        def fly(self):
            print('fly')
            self.action = 'fly'# 定义在函数里的变量,需要调用完函数才会生成
        def swim(self):
            self.action = 'swim'
        def about(self):
            print('%s %s'%(self.color,self.wheel))
            print('汽车现在的功能是 %s'%self.action) #调用完fly、swim函数后才能action的属性
        def calc(self,a,b):
            print(a+b)
    
    bmw = Car('red')
    bmw.run()
    bmw.fly()
    bmw.swim()
    bmw.about()
    
    bmw.calc(1,2)

    面向对象实例:连接操作mysql的类

    class MyDb:
        # def __init__(self, ip, user, password, db, port=3306, charset='utf8', autocommit=True):
        def __init__(self,**info):
            try:
                self.conn = pymysql.connect(**info)
                # self.conn = pymysql.connect(host=ip,user=user,password=password,db=db,port=port,charset=charset,autocommit=autocommit)
                self.cursor = self.conn.cursor(pymysql.cursors.DictCursor)
            except Exception as e :
                print('数据库连接失败!')
                raise Exception('数据库连接失败!%s'%e)
    
        def __del__(self):
            print('--del--')
            self.cursor.close()
            self.conn.close()
    
        def execute_one(self,sql):
            result = '执行成功'
            if sql.strip().lower().startswith('select'):
                try:
                    self.cursor.execute(sql)
                except Exception as e :
                    print('sql语句出错!%s'%e)
                else:
                    result = self.cursor.fetchone()
            return result
    
        def execute_many(self,sql):
            result = '执行成功'
            if sql.strip().lower().startswith('select'):
                try:
                    self.cursor.execute(sql)
                except Exception as e :
                    print('sql语句出错!%s'%e)
                else:
                    result = self.cursor.fetchall()
            return result
    
        def table_exists(self,table_name):
            sql = "SELECT table_name FROM information_schema.TABLES WHERE table_name ='%s';" % table_name
            if self.execute_one(sql):
                return True
    
    my_sql = MyDb(**setting.mysql_info)
    res2 = my_sql.table_exists('app_myuser')
    print(res2)
    res = my_sql.execute_one('select * from app_myuser')
    #res = my_sql.execute_one("insert into qq_mem_dongxl(qq,nick,join_time,gender,card) values('1111','aaaa','2019-4-10','女','茶叶');")
    print(res)

    类变量、类方法、实例变量、属性方法

    class Car:
        wheel = 4 #类变量,存在类里面
        window = 4
    
        def say(self):
            print('有%s个轮子'%self.wheel)
            self.interview()
    
        def set_wheel(self,wheel,window):
            Car.wheel = wheel #修改类的变量
            self.window = window #给实例加了一个变量,实例变量
    
        @classmethod#类方法,不需要实例化就能使用
        def interview(cls):
            print('这个车有%s个轮子'%cls.wheel)
    
        #属性方法,使用时像变量一样,必需有返回值
        @property
        def name(self):
            return 'xiaobai'
    
    print(Car.wheel)#4类变量可以不实例化,直接使用
    Car.interview()#类方法,可以不实例化,直接调用
    b = Car()
    print(b.name)#属性方法,直接当变量使用
    b.set_wheel(3,2)
    print(b.wheel)#3
    print(b.window)#2

     私有变量、私有函数

    import redis
    class MyRedis:
        name = 'haha'
        def __init__(self,ip,password,port=6379):
            self.__ip = ip#私有变量,只能在类里面使用
            self.__port = port
            self.__password = password
            self.conn_redis()
        def conn_redis(self):
            self.r = redis.Redis(host=self.__ip,password=self.__password,port=self.__port)
        def get_str(self,key):
            return self.r.get(key)
        def say(self):
            print('ip',self.__ip)
            self.__dd()
        # 私有方法,只能在类里面使用,实例化不能使用
        def __dd(self):
            print('dd')
    
    
    r = MyRedis('118,24,3,40','HK139bc&*')
    print(r.__ip)#不能这样使用,私有变量只能在类里被使用
    r.__dd()#不能这样使用,私有方法只能在类里被调用
    r.say()

    继承

    class Lw:
        country = 'china'
        money = 100000
    
        def driver(self):
            print('开车')
    
        def makeMoney(self):
            print('zhengqian')
    
    #继承
    class Xw(Lw):
       print(Lw.money)#使用父类变量
      def makeM(self):
      super().makeMoney()#用super()使用父类方法
    def driver(self): #重写父类方法
            print('自己开车')
    
    xw = Xw()
    xw.driver()#调用自己的函数
    print(xw.money)
    xw.makeMoney()#调用父类函数
    
    
    class DbBase:
        def __init__(self,ip,port,password,db):
            self.ip = ip
            self.port = port
            self.password = password
            self.db = db
    
    class MySQL(DbBase,Lw):#继续多个父类
        #重写父类方法
         #1、父类的方法一点都不用
         #2、在父类的方法基础上做扩展
        #super() 找到父类
        def __init__(self,ip,port,password,db,user):
            super().__init__(ip,port,password,db)#用super()找到父类,再调用父类的构造方法(或者其它方法)
            self.user = user
    m = MySQL('11.11.11.11','3306','password','db','nana')
    m.driver()
    print(m.ip)
    print(m.user)


  • 相关阅读:
    C# MenuStrip Visible=false bug的解决方案
    WTL 命令行编译
    LCS 最长公共字串算法实现
    调用系统打开文件OpenAs_RunDLL
    ToolStripSplitButton Checked 效果
    WTL 中使用GDI+ 备忘
    P7482 不条理狂诗曲 题解
    CF1557 比赛记录
    P2519 [HAOI2011]problem a 题解
    CF1540B Tree Array 题解
  • 原文地址:https://www.cnblogs.com/yanyan-/p/10931752.html
Copyright © 2011-2022 走看看