Python 面向对象编程 day7

一、类方法:类自带的方法,即类方法

class Car:
    def run(self): #实例方法中,调用本类变量、类方法都要用self.XXX调用
        print("run")
        hm=Person('hanmin')   #实例方法中,调用其他类的实例方法
        print(self.country)            #这个country是本类中的country
        print(hm.country)            #这个country是Person这个类中的country
        self.shuoming()  #类方法是公共的,实例方法中也可以调用类方法
        #run=self       #self代表本身的类,可以XXX=self,就是实例化这个类
        #run.shuoming()#类方法是公共的,实例方法中也可以调用类方法
  #在类中,函数的调用不是按顺序执行的,可以直接调用后边代码中的变量或方法


    @classmethod  
 #加了装饰器的方法就是类方法。类方法也是公共的。类中的方法都可以调用。但是不能直接调用实例方法和实例变量.
#类方法在调用时,不需要实例化,直接  类名.方法名()即可调用
        def shuoming(cls)    #cls代表此类本身,与实例方法中的self类似
            #类方法中只能直接调用类变量、类方法
            print("怎么造汽车")
            print("造%s的汽车"%cls.country)
            bmw=cls     #cls代表本身的类,其实相当于把这个类实例化
            bmw.run()    #实例方法实例化后,可以调用实例方法

二、静态方法

@staticmethod    #写在类中的普通方法,不需要实例化,不能调用类方法,也不能调用实例方法。但是类方法、实例方法都能调用静态方法
    def act():
         print('静态方法')
 Car.act()  #调用时直接用类名.方法名

三、属性方法

看起来像变量的一个方法。不能有传参,不能有入参

    @property
    def name(self):
        return '大黄蜂'
print(c.name)   #属性方法,调用时直接调用函数名,不能加括号

四、例子

import pymysql
class MySQL:
    def __init__(self ):    
        self.conn=pymysql.connect(host='117.25.23.20,user='XXX',password='45461
', db='jxz',port=3306,charset='utf8',
                       autocommit=True)
            self.cur=self.conn.cursor(pymysql.cursors.DictCursor)
    def __del__(self):   #析构方法:
        print('什么时候执行析构方法')
    def excute_one(self,sql):
        self.cur.execute(sql)
        return self.cur.fetchone()
    def execut_many(self,sql):
        self.cur.execute(sql)
        return self.cur.fetchall()
    def close(self):
        self.cur.close()
        self.conn.close()
    def __del__(self):    #当实例被执行完后,执行此代码
        self.cur.close()
        self.conn.close()
        print('连接已被关闭')
m=MySQL()
print(m.excute_one('select * from app_myuser'))