Última actividad 8 months ago

示範 Python 中 dataclass 與 NamedTuple 的基本使用方式與差異,包含屬性定義、建立實例、存取欄位、是否可變等特性。

Revisión 48f4e2781a79df9f6a10784ab020f0f74a4768f7

dataclass_person_example.py Sin formato
1from dataclasses import dataclass
2
3@dataclass
4class Person:
5 name: str
6 age: int
7 email: str
8
9# 建立實例
10person1 = Person(name="Timmy", age=30, email="timmy@example.com")
11
12# 修改值也可以(可變)
13person1.age = 31
14print(person1)
15
named_tuple_person_example.py Sin formato
1from typing import NamedTuple
2
3class Person(NamedTuple):
4 name: str
5 age: int
6 email: str
7
8# 建立實例
9person1 = Person(name="Timmy", age=30, email="timmy@example.com")
10
11# 存取欄位值(像是屬性一樣)
12print(person1.name) # Timmy
13print(person1.age) # 30
14print(person1.email) # timmy@example.com
15
16# NamedTuple 也是可被解包的(像一般 tuple)
17name, age, email = person1
18print(f"{name} is {age} years old. Email: {email}")
19