1. The meaning of object-oriented programming, can Baidu
2. Classes: Class compared to the real world is a kind, a model.
3. Instantiation: The process of making a model into something real is called instantiation.
4. Instance/object: something that is specifically made, instantiated through the class
Like what:
Class Car (): #造车, requires a model, which is the class
def run (self):
Print (' The car is running ... ‘)
Bus = Car () # #把模型做成实际的一个汽车, this process is called instantiation
#bus是一个实例/Object
Bus.run () #造好汽车后, want to let the car run directly call function on the line
Programming operations, Notes:
Class Car (): #造车, requires a model, which is the class
def __init__ (Self,color,window):
#构造函数, the class executes when it initializes (instantiates)
#如果你的类在实例化的时候要传入一些参数, you're going to write the arguments in the __init__ function.
Self.color = Color
Self.window = window
Print (' test execution this sentence ')
def run (self):
Print (' The car is running ... ‘)
def my_self (self):
Print (' I am a car, my color is '%s ', I have%s windows '% (Self.color,self.window))
Bus = Car (' Red ', ' 3 Open Door ') # #把模型做成实际的一个汽车, this process is called instantiation
Bus.my_self ()
Execution Result:
============================ I'm a split line ================================================================
Use class to write MySQL:
Class Opmysql (object):
def __init__ (self,host,user,password,db,port=3360,charset= ' UTF8 '): #必填参要放在默认参前面
schema = {
' User ': User,
' Host ': Host,
' Password ':p assword,
' DB ':d B,
' Port ':p ort,
' CharSet ': CharSet
}
Try
Self.conn = Pymysql.connect (**schema)
Except Exception as E:
Print (' Database connection exception! %s '%e)
Quit (' Database connection exception! %s '%e)
else: #没有出异常的情况下, creating cursors
Self.cur = Self.conn.cursor (cursor=pymysql.cursors.dictcursor)
def execute (self,sql):
Try
Self.cur.execute (SQL)
Except Exception as E:
Print (' SQL statement has error%s '%e)
Return E
If sql[:6].upper () = = ' SELECT ':
Return Self.cur.fetchall ()
else: #其他sql语句commit一下
Self.conn.commit ()
Return ' OK '
def close (self):
Self.cur.close ()
Self.conn.close ()
MPP = Opmysql (' 211.149.218.16 ', ' jxz ', ' 123456 ', db= ' jxz ')
Print (Mpp.execute (' select * from Stu; '))
Mpp.close ()
Object-oriented programming of Python