python ------ > the third day, object-oriented, graphical programming, database

object-oriented


    -> Class abstraction and definition
         1. Based on what
             (according to various business logic), that is, a pile of instances
         2. What should class abstraction be
             The abstract is to provide the commonness of a pile of instances
                 Common attributes
                 Common method

         3. How to convert natural language into a language used by programmers, which can be seen and used to pack classes:
             UML (Unified Modeling Language) (one diagram)
             Be able to understand (requirements at work)

         4. Use different syntax to implement
            C++
            python
            Java
             etc.


    -> Instantiation process
         1. Instantiation
             Construct an instance of this class   

  1. Definition of class
         example:

  #define_class.py

            class People():
                pass

            p1 = People()
            print(type(p1))
        Output results:
            <class '__main__.People'>

     2. Example method
         example:   

  #define_class.py

            class People():
                def syaHello(self):            #self is the default parameter and must have
                    print('Hello!')

            p1 = People()
            p1.syaHello()

        Output results:
            Hello!

     3. Constructor
         You can use the constructor to initialize a class:
         example:      

  #define_class.py

                class People():
                    def __init__(self,sex):
                        self.sex = sex            #Instance variable

                    def syaHello(self):            #self is the default parameter and must have
                        print('Hello!')

                p1 = People('man')
                p1.syaHello()
                print(p1.sex)
        Output results:
            Hello!
            man

4. Class variable
     example:

  #define_class.py

        class People():
            sum = 0
            def __init__(self,sex):
                self.sex = sex            #Instance variable
                People.sum += 1            #People.sum can also be written as self.sum
                print('Now there are%d Personal.'%People.sum)
            def syaHello(self):            #self is the default parameter and must have
                print('Hello!')

        p1 = People('man')
        p1.syaHello()
        p2 = People('woman')
        print(p1.sex)

    Output results:
        There is one person now.
        Hello!
        There are two people now.
        man

5. Class method
     example:

 #define_class.py

        class People():
            sum = 0
            def __init__(self,sex):
                self.sex = sex            
                self.__class__.sum += 1            
                print('Now there are%d Personal.'%self.__class__.sum)
            def syaHello(self):            #self is the default parameter and must have
                print('Hello!')
            @classmethod
            def plus(cls):
                cls.sum += 1
                print("Now there are%d Personal."%cls.sum)


        p1 = People('man')
        People.plus()
        p2 = People('woman')
        People.plus()
    Output:
        There is one person now.
        There are two people now.
        There are three people now.
        There are four people now.

To define a class method, you need to add @ classmethod to the class method. This is a decorator. You will learn later that it is best to use cls as the default value, and there will be no error when using other methods. The class name and class method name are used to call class methods

6. Static method
     Static methods are basically similar to class methods. The basic of static methods can also be replaced by class methods. Static methods should be used as little as possible
    

example:  

  class People():
            sum = 0
            def __init__(self,sex):
                self.sex = sex            
                self.__class__.sum += 1            
                print('Now there are%d Personal.'%self.__class__.sum)
            def syaHello(self):            #self is the default parameter and must have
                print('Hello!')
            @classmethod
            def plus(cls):
                cls.sum += 1
                print("Now there are%d Personal."%cls.sum)
            @staticmethod
            def stat():
                People.sum += 1
                print("Now there are%d Personal."%People.sum)


        p1 = People('man')
        People.stat()
    Output:
        There is one person now.
        There are two people now.


cls.xxx can be directly used when calling class variables with class methods, but static methods have no default parameters. When calling class variables, the full name of the class must be written out, and @ staticmethod must be added to the static method when defining static methods

7. Private ownership
     Add _ before the instance method or variable, It is declared private and cannot be accessed directly through variables or method names
     But being private doesn't mean you really can't access it externally      example:
      

 #private_method.py

        class People(object):
            """docstring for People"""
            def __init__(self):
                self.__sex = 'man'
            def __sayHello(self):
                print("Hello!")

        p1 = People()
        print(p1.__dict__)
        print(p1._People__sex)
        p1._People__sayHello()
    Output:
        {'_People__sex': 'man'}
        man
        Hello!

Find one in the class through dict_ People__ The property of sex, which is actually the private variable we set, can be accessed directly from the outside, as can the instance method

8. Succession
    

example:

  #Filename:cls.py

        class People():
            def __init__(self,name,age):
                self.name=name
                self.age=age
            def sayHello(self):
                print('Hello!')


        #Filename: stu.py
        import cls

        class Student(cls.People):
            pass

        stu=Student('Tom',18)
        stu.sayHello()

    Output results:
        Hello!


The Student class inherits the methods of the People class
    

import cls

    class Student(cls.People):
        def __init__(self,name,age,score):
            self.score=score
            cls.People.__init__(self,name,age)

        def sayHello(self):
            print('Hi!')

    stu=Student('Tom',18,90)
    stu.sayHello()
Output results:
    Hi!

The subclass extends the init() method of the parent class, but when calling the init method of the parent class, you must pass in self
The subclass then overrides the sayHello() method of the parent class
super() can also be used when calling methods of the parent class
  

 import cls

    class Student(cls.People):
        def __init__(self,name,age,score):
            self.score=score
            super(Student,self).__init__(name,age)

        def sayHello(self):
            print('Hi!')

    stu=Student('Tom',18,90)
    stu.sayHello()
    print(stu.name)
    print(stu.age)

Output results:
    Hi!
    Tom
    18

9. Multiple inheritance
     python can inherit more
     example:
      

 class A():
            def __init__(self):
                print('a')

        class B():
            def __init__(self):
                print('b')

        class C(A,B):
            pass

        c=C()
    Output results:
        a


If the parent class has the same method, the child class will call the method of the inherited class first

10. Polymorphism
     example:

 class C():
            def say(self):
                pass

        class B(C):
            def say(self):
                print('B')

        class A(C):
            def say(self):
                print('A')

        b=B()
        a=A()
        b.say()
        a.say()
    Output:
        B
        A

example:

​
class animal:
    #Pass is used to occupy the position. If you do not want to implement the function body and statement block, you can use pass to occupy the position
    #pass
    '''
        count It belongs to a class variable. When using it, there must be a class name constraint in front of it
        Class variables are common to the entire class
    '''
    count = 0
    def __init__(self):
        #myclass is an instance variable. self constraint is required when using it
        self.myclass = "animal"
        self.__name = "Zhang San"
        animal.count += 1

    '''
        Class, the method used for the instance
    '''
    def speak(self):
        print("@#$")

    @classmethod
    def print_count(cls):
        print(cls.count)

    @staticmethod
    def study():
        print("good good study, day day up")

    def __mytest(self):
        print("take a paper for listen word")

class dog(animal):
    def __init__(self):
        '''
            If only part of the initialization parameters are changed in the parent class constructor, execute the parent class initialization function
            super().__init__()
        '''
        super().__init__()
        self.__name = "Wangcai"
        self.myclass = "Dog"

    #The subclass overrides the parent class speak method
    def speak(self):
        print("Woof")

    #The child class overrides the parent class__ mytest private method
    def __mytest(self):
        print("Bite, wag your tail, shout, bow")

​
'''
    from myanimal Import from file animal Class and rename it to ani,And the current file can only be used ani Represents this class,
    You cannot use the original class name
'''


from myanimal import animal as ani

#Instantiate an ani()
a = ani()
print(type(a))
a.speak()
print(a.myclass, a.count)
b = ani()
c = ani()
'''
    Instances can call class methods
    Class can call class methods
'''
c.print_count()
ani.print_count()
'''
    Class cannot call instance methods, that is, there are in the method parameters self of
    ani.speak()
'''

'''
    Instances can call static methods
    Class can call static methods
'''
c.study()
ani.study()

'''
    Format of call to private method:
        Instance name._Class name(Cannot be an incoming alias)Private method name()

    Private methods have self: Cannot be used by classes   
'''
#c.__mytest()
c._animal__mytest()
#ani._animal__mytest()

#Printout private variables
print(c._animal__name)
from myanimal import *

d1 = dog()
d2 = dog()
d1.speak()
d1.print_count()
d1.study()
print(d1.myclass)
print(d1._dog__name)
d1._animal__mytest()

Graphical programming


     The graphical programming under python mainly uses the tkinter package

     Tk(): page class


     1. Create a page
        root = Tk()
        root.mainloop()

from tkinter import *

'''
    Tk():Create a form called root
'''
root = Tk()

#Use title to set the title of the form
root.title("This is my first python GUI page")

#Use the geometry() method to set the size of the form. The parameter is a string "width x height"
root.geometry("400x300")

'''
    The created form must be mainloop,If not mainloop Method, the form cannot be displayed
'''
root.mainloop()

     2. To implement complex pages, you need controls
        Button
        Entry
        Label
        Text
        Toplevel

     3. Common properties of control
         bg: background color
         Font: font
         fg: foreground color
         height: high
         image: picture
         Width: width
         text: text
     4. Use python to display a picture
             Install PIL Library
                pip install Pillow        

example:

            from tkinter import *
            from PIL import Image, ImageTk

            root = Tk()
            root.title("Face recognition")
            img_open = Image.open('1.jpg')
            photo = ImageTk.PhotoImage(img_open)
            img_label = Label(root, imag=photo)
            img_label.pack()#pack() can display the control on the form by default
            root.mainloop()

     5. Input box
         How to get the value of the input box
    6.Button
         How to bind associated events

     7.Button binding event
         Button(command = function name)
     8.Text control
        get(0.0,END)
        insert(END,str)

Picture operation and Label label:

import tkinter as tk
from PIL import Image,ImageTk 

con = "Look at me\n Old poison, take your life\n You can kill if you want. Don't talk nonsense"

root = tk.Tk()
root.title("Classic quotations of flying bat")
root.geometry("300x600")

imge = Image.open("1.jpg")
photo = ImageTk.PhotoImage(imge)
lb1 = tk.Label(image=photo)
#pack() can display the control on the form by default
lb1.pack()
lb = tk.Label(text=con,bg="#ff2278", fg="blue", font =" Arial ", 24)
#place() can display the control on the form in the specified way
lb.place(relx=0.01,rely=0.41,relwidth=0.98, relheight=0.58)
root.mainloop()

Text edit box:

from tkinter import *

def get_con():
    con = te.get(0.0,END)
    print(con)

def show_in_text():
    con = ent.get()
    te.insert(END,"\n"+con)

root = Tk()
root.title("Text edit box")
root.geometry("400x500")
ent = Entry(root)
ent.place(relx=0.01,rely=0.52,relwidth=0.5, relheight= 0.1)
te = Text(root)
te.place(relx=0.01,rely=0.01,relwidth=0.98,relheight=0.5)
bnt = Button(text="Output input in Text Content in",command=get_con)
bnt.place(relx=0.01,rely=0.63,relwidth=0.5)
bnt1 = Button(text="Append in Text in",command=show_in_text)
bnt1.place(relx=0.52, rely=0.63, relwidth=0.3)
root.mainloop()

Entry, button, Label:

from tkinter import *
from PIL import Image, ImageTk
import time
import threading

namelist = ['kze-jqg ','ren woxing','Balala little magic fairy','Mother Rong','Sailor Moon']

def func():
    #while True:
    con = entr1.get()
    lb.configure(text=con)
    '''
    for i in range(len(namelist)):
        if(con == namelist[i]):
            fn = str(i+1)+".jpg"
            print(fn)
            img = Image.open(fn)
            ph = ImageTk.PhotoImage(img)
            lb.config(image=ph)
            time.sleep(10)
    '''

root = Tk()
root.geometry("300x500")
root.title("Input boxes and buttons")

entr1 = Entry(root)
bnt1 = Button(text="Show to label upper",command=func)
lb = Label(root)

'''
Load pictures using threads
tid1 = threading.Thread(target=func)
tid1.start()

def close_tid():
    tid1.join()

'''

entr1.place(relx=0.01,rely = 0.01, relwidth=0.6, relheight= 0.06)
bnt1.place(relx=0.62,rely=0.01,relwidth=0.37)
lb.place(relx=0.01,rely=0.08,relwidth=0.98, relheight=0.91)
root.mainloop()

How to access sqlite3 database


     python database operation:
         Python versions above 2.5. X have sqlite3 module by default.
         API of python sqlite3 module:
            1.sqlite3.connect(database,[timeout,other optional arguments])
                 This API opens a link to the SQLite database file database. You can use ": memory:" to open a link in RAM
                 A database link to the database instead of opening it on disk. If the database is opened successfully, a connection object is returned.
                 When a database is accessed by multiple connections and one of them modifies the database, the SQLite database is locked until the transaction is committed. The timeout parameter indicates the duration of the connection waiting for locking until an abnormal disconnection occurs. The timeout parameter defaults to 5.0 (5 seconds).
                 If the given database name filename does not exist, the call creates a database. If you do not want to create a database in the current directory, you can specify a file name with a path so that you can create the database anywhere.
            2.connection.cursor([cursorClass])
                 This routine creates a cursor that will be used in Python database programming. This method accepts a single optional parameter cursorClass. If this parameter is provided, it must be a custom cursor class that extends from sqlite3.Cursor.
            3.cursor.execute(sql [, optional parameters])
                 This routine executes an SQL statement. The SQL statement can be parameterized (that is, use placeholders instead of SQL text). The sqlite3 module supports two types of placeholders: question marks and named placeholders (named styles).
                 For example: cursor. Execute ("insert into people values (?,?), (who, age))
            4.connection.commit()
                 This method commits the current transaction. If you do not call this method, any action you have taken since you last called commit() will not be visible to other database connections.
            5.connection.close()
                 This method closes the database connection. Note that this does not automatically call commit(). If you do not call the commit() method before, close the database connection directly, and all your changes will be lost!
            6.cursor.fetchall()
                 This routine gets all (remaining) rows in the query result set and returns a list. When no rows are available, an empty list is returned.

         When using sqlite in python, open it before use and close it after use to avoid database locking as much as possible.         

Example: create a database and create a table
          

 #create_db_tab.py

            import sqlite3

            conn = sqlite3.connect("mytest.db")
            print("Open database successfully")

            c = conn.cursor()
            c.execute("create table company(ID INT PRIMARY KEY NOT NULL,NAME TEXT NOT NULL,AGE INT NOT NULL,ADDRESS CHAR(50),SALARY REAL);")
            print("Table create successfully")
            conn.commit()
            conn.close()

         Example: insert data
          

 import sqlite3

            conn = sqlite3.connect("mytest.db")
            print("Open database successfully")

            c = conn.cursor()
            c.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
                  VALUES (1, 'Paul', 32, 'California', 20000.00 )")
            c.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
                  VALUES (2, 'Allen', 25, 'Texas', 15000.00 )")
            c.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
                  VALUES (3, 'Teddy', 23, 'Norway', 20000.00 )")
            c.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
                  VALUES (4, 'Mark', 25, 'Rich-Mond ', 65000.00 )")
            conn.commit()
            print("Records created successfully")
            conn.close()

         Example: query data item
          

  import sqlite3

            conn = sqlite3.connect('mytest.db')
            c = conn.cursor()
            print("Opened database successfully")

            cursor = c.execute("SELECT id, name, address, salary  from COMPANY")
            for row in cursor:
               print("ID = ", row[0])
               print("NAME = ", row[1])
               print("ADDRESS = ", row[2])
               print("SALARY = ", row[3], "\n")

            print("Operation done successfully")
            conn.close()

         Example: change data item
         

   import sqlite3

            conn = sqlite3.connect('mytest.db')
            c = conn.cursor()
            print("Opened database successfully")

            c.execute("UPDATE company set SALARY = 25000.00 where ID=1")
            conn.commit()
            print("Total number of rows updated :", conn.total_changes)

            cursor = conn.execute("SELECT id, name, address, salary  from COMPANY")
            for row in cursor:
               print("ID = ", row[0])
               print("NAME = ", row[1])
               print("ADDRESS = ", row[2])
               print("SALARY = ", row[3], "\n")

            print("Operation done successfully")
            conn.close()


         Example: delete data item
          

 import sqlite3

            conn = sqlite3.connect('mytest.db')
            c = conn.cursor()
            print("Opened database successfully")

            c.execute("DELETE from COMPANY where ID=2;")
            conn.commit()
            print("Total number of rows deleted :", conn.total_changes)

            cursor = conn.execute("SELECT id, name, address, salary  from COMPANY")
            for row in cursor:
               print("ID = ", row[0])
               print("NAME = ", row[1])
               print("ADDRESS = ", row[2])
               print("SALARY = ", row[3], "\n")

            print("Operation done successfully")
            conn.close()

Tags: Python

Posted on Wed, 15 Sep 2021 03:16:03 -0400 by fernandodonster