python头歌练习六

1.Encapsulation and Inheritance of Classes

1.1the_car_class
class Car:
    def __init__(self, make, model, year):
        self.make = make
        self.model = model
        self.year = year

    def display_info(self):
        print(f"Car Make: {self.make}, Model: {self.model}, Year: {self.year}")
1.2encapsulation_car_class
class Car:
    def __init__(self, make, model, year):
        self.__make = make
        self.__model = model
        self.year = year

    def display_info(self):
        print(f"Car Make: {self.__make}, Model: {self.__model}, Year: {self.year}")

    def get_make(self):
        return self.__make

    def set_make(self, make):
        self.__make = make

    def get_model(self):
        return self.__model

    def set_model(self, model):
        self.__model = model

   
1.3inheritance_car_class
"""
File: inherit_car_class.py
"""
# 根据类中方法名和任务要求,补充完整各方法内部代码
# 类中方法名不能修改
class Car:  
    def __init__(self, make, model, year):  
        self.__make = make  
        self.__model = model  
        self.year = year        
    def get_make(self):  
        return self.__make
    def get_model(self):  
        return self.__model
    def display_info(self):  
        print(f"Car Make: {self.__make}, Model: {self.__model}, Year: {self.year}")  


class ElectricCar(Car): # 补充代码实现继承Car类
    # 根据类中方法名和任务要求,补充完整各方法内部代码
    # 类中方法名不能修改  
    def __init__(self, make, model, year, battery_size):
        super().__init__(make, model, year)
        self.battery_size = battery_size

    def display_info(self):
        super().display_info()
        print(f"Battery Size: {self.battery_size} kWh") 
         
        
    

2.database operation

2.1create_database
"""
File: create_database.py
"""
import sqlite3

def create_database():
    # Connect to SQLite database (it will create the database if it doesn't exist)
    conn = sqlite3.connect('school.db')
    cursor = conn.cursor()
    # Create table
    cursor.execute('''
        CREATE TABLE IF NOT EXISTS students (
            id INTEGER PRIMARY KEY,
            name TEXT NOT NULL,
            age INTEGER NOT NULL,
            grade TEXT NOT NULL
        )
    ''')
    conn.commit()
    conn.close()

def insert_student(student_id, name, age, grade):
    conn = sqlite3.connect('school.db')
    cursor = conn.cursor()
    try:
        cursor.execute('''
            INSERT INTO students (id, name, age, grade) VALUES (?, ?, ?, ?)
        ''', (student_id, name, age, grade))
        conn.commit()
    except sqlite3.IntegrityError:
        print(f"Student '{student_id}:{name}' already exists!")
    finally:
        conn.close()

def get_students():
    conn = sqlite3.connect('school.db')
    cursor = conn.cursor()
    cursor.execute('SELECT * FROM students')
    rows = cursor.fetchall()
    students = []
    for row in rows:
        student = {'id': row[0], 'name': row[1], 'age': row[2], 'grade': row[3]}
        students.append(student)
    conn.close()
    return students

# Uncomment the following lines to test the functions
# create_database()
# insert_student(1, 'John Doe', 20, 'Sophomore')
# insert_student(2, 'Jane Smith', 22, 'Senior')
# print(get_students())
2.2update_database
"""
File: update_database.py
"""
import sqlite3

# Task 1: Update data  
def update_student_age(student_id, new_age):
    # Connect to the SQLite database
    conn = sqlite3.connect('school.db')
    cursor = conn.cursor()
    try:
        # Update the age of the student with the given student_id
        cursor.execute('UPDATE students SET age = ? WHERE id = ?', (new_age, student_id))
        conn.commit()
    except sqlite3.Error as e:
        print(f"An error occurred: {e}")
    finally:
        conn.close()

# Task 2: Delete data  
def delete_student(student_id):
    # Connect to the SQLite database
    conn = sqlite3.connect('school.db')
    cursor = conn.cursor()
    try:
        # Delete the student with the given student_id
        cursor.execute('DELETE FROM students WHERE id = ?', (student_id,))
        conn.commit()
    except sqlite3.Error as e:
        print(f"An error occurred: {e}")
    finally:
        conn.close()

# Task 3: Query a student data
def get_student(student_id):
    # Connect to the SQLite database
    conn = sqlite3.connect('school.db')
    cursor = conn.cursor()
    try:
        # Query the student information with the given student_id
        cursor.execute('SELECT * FROM students WHERE id = ?', (student_id,))
        row = cursor.fetchone()
        if row:
            student = {'id': row[0], 'name': row[1], 'age': row[2], 'grade': row[3]}
            return student
        else:
            return None
    except sqlite3.Error as e:
        print(f"An error occurred: {e}")
        return None
    finally:
        conn.close()

# Uncomment the following lines to test the functions
# update_student_age(1, 21)
# student_info = get_student(1)
# print("Student information after updating age:", student_info)
# delete_student(2)
# students_list = get_students()
# print("Students after deleting Jane:", students_list)
2.3counting_database_data
"""
File: counting_database_data.py
"""
import sqlite3

# Task 1: Count data  
def count_students_by_grade(grade):
    # Connect to the SQLite database
    conn = sqlite3.connect('school.db')
    cursor = conn.cursor()
    try:
        # Count the number of students with the given grade
        cursor.execute('SELECT COUNT(*) FROM students WHERE grade = ?', (grade,))
        count = cursor.fetchone()[0]
        return count
    except sqlite3.Error as e:
        print(f"An error occurred: {e}")
        return None
    finally:
        conn.close()

# Uncomment the following lines to test the function
# Assuming you have already inserted data into the database, you can test the function like this:
# print("Count of Sophomores:", count_students_by_grade('Sophomore'))

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

南宫真汀

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值