การใช้งาน dataclasses
มาใช้งาน dataclass WeightEntry ที่สร้างไว้ในแบบฝึกหัดก่อนหน้ากัน เราจะสร้าง instance ของ WeightEntry สำหรับแต่ละรายการใน weight_log จากนั้นใช้ property mass_to_flipper_length_ratio ที่เพิ่มไว้เพื่อคำนวณค่า ด้านล่างนี้คือ dataclass WeightEntry ของเราเพื่อเป็นการทบทวน
@dataclass
class WeightEntry:
# Define the fields on the class
species: str
flipper_length: int
body_mass: int
sex: str
@property
def mass_to_flipper_length_ratio(self):
return self.body_mass / self.flipper_length
แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร
ประเภทข้อมูลใน Python
คำแนะนำการฝึกหัด
- สร้างลิสต์ว่างชื่อ
labeled_entries - วนซ้ำผ่านรายการใน
weight_logโดยใช้การขยาย tuple เพื่อแยกค่าspecies,flipper_length,body_mass,sex- เพิ่ม instance ใหม่ของ dataclass
WeightEntryสำหรับแต่ละรายการลงในlabeled_entries
- เพิ่ม instance ใหม่ของ dataclass
- แสดง 5 ค่าแรกของ
mass_to_flipper_length_ratioโดยใช้ list comprehension
แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ
ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์
# Create the empty list: labeled_entries
labeled_entries = []
# Iterate over the weight_log entries
for species, flipper_length, body_mass, ____ in weight_log:
# Append a new WeightEntry instance to labeled_entries
____.____(____(species, flipper_length, body_mass, ____))
# Print a list of the first 5 mass_to_flipper_length_ratio values
print([____.____ for entry in labeled_entries[____]])