Object-oriented at the code level
1, in the absence of learning the concept of class, the data and function are separated
EF Exc1 (host,port,db,charset): conn=connect (Host,port,db,charset) conn.execute (SQL) return xxxdef Exc2 (host,port,db,charset,proc_name) conn=connect (host,port,db,charset) conn.call_proc (SQL) return xxx# each call needs to pass through a bunch of parameters exc1 (' 127.0.0.1 ', 3306, ' db1 ', ' UTF8 ', ' select * from TB1; ') Exc2 (' 127.0.0.1 ', 3306, ' db1 ', ' UTF8 ', ' name of stored procedure ')
2, can think of the solution is that these variables are defined as global variables
host= ' 127.0.0.1 ' port=3306db= ' db1 ' charset= ' UTF8 ' def exc1 (host,port,db,charset): conn=connect (HOST,PORT,DB, CharSet) conn.execute (SQL) return xxxdef exc2 (host,port,db,charset,proc_name) Conn=connect (host,port , Db,charset) conn.call_proc (SQL) return xxxexc1 (Host,port,db,charset, ' select * from TB1; ') Exc2 (Host,port,db,charset, ' name of stored procedure ')
3, but 2 of the solution is also problematic, according to 2 of the idea, we will define a lot of global variables, these global variables do not make any distinction, that can be used by all functions, but in fact only Host,port,db,charset is to Exce1, and Exc2 These two functions, the implication: we have to find a way to combine the data with the methods of manipulating the data, that's the class we're talking about.
From Pymysql import Connectclass mysqlhandler: def __init__ (self, host, port, DB, charset= "Utf-8"): self.host = h OST Self.port = port self.db = db Self.charset = CharSet self.conn = Connect (self.host, Self.port, Self.db, Self.charset) def exc1 (self, SQL): return Self.conn.execute (SQL) def exc2 (self, SQL): return self.conn.call_proc (sql) obj = mysqlhandler (' 127.0.0.1 ', 3306, ' db1 ') obj.exc1 (' select * from Tab1 ') Obj.exc2 (' The name of the stored procedure ')
Summary usage classes can:
Integrate data with features that specialize in manipulating that data
High scalability
Defining a class and producing three objects
Class Chinese: def __init__ (self,name,age,sex): self.name=name self.age=age self.sex=sexp1= Chinese (' Egon ', ' Male ') P2=chinese (' Alex ', ' a ', ' female ') P3=chinese (' Wpq ',, ' female ')
If we add a new class attribute, it will be immediately reflected to all objects, but the object does not need to be modified
Class Chinese: country = ' China ' def __init__ (self, name, age, Sex): self.name = name self.age = Age Self.sex = Sex def tell_info (self): info = ' Nationality:%s Name:%s Age:%s Gender:%s ' ' % ( Self.country, Self.name, Self.age, self.sex) print (info) p1 = Chinese (' Egon ', ', ' male ') P2 = Chinese (' Alex ', ", ' FE Male ') P3 = Chinese (' wpq ', ' Female ') print (p1.country) p1.tell_info ()
Python Object-oriented: summary