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'))