timmy 已修改 8 months ago. 還原成這個修訂版本
沒有任何變更
timmy 已修改 8 months ago. 還原成這個修訂版本
2 files changed, 32 insertions
dataclass_person_example.py(檔案已創建)
| @@ -0,0 +1,14 @@ | |||
| 1 | + | from dataclasses import dataclass | |
| 2 | + | ||
| 3 | + | @dataclass | |
| 4 | + | class Person: | |
| 5 | + | name: str | |
| 6 | + | age: int | |
| 7 | + | email: str | |
| 8 | + | ||
| 9 | + | # 建立實例 | |
| 10 | + | person1 = Person(name="Timmy", age=30, email="timmy@example.com") | |
| 11 | + | ||
| 12 | + | # 修改值也可以(可變) | |
| 13 | + | person1.age = 31 | |
| 14 | + | print(person1) | |
named_tuple_person_example.py(檔案已創建)
| @@ -0,0 +1,18 @@ | |||
| 1 | + | from typing import NamedTuple | |
| 2 | + | ||
| 3 | + | class Person(NamedTuple): | |
| 4 | + | name: str | |
| 5 | + | age: int | |
| 6 | + | email: str | |
| 7 | + | ||
| 8 | + | # 建立實例 | |
| 9 | + | person1 = Person(name="Timmy", age=30, email="timmy@example.com") | |
| 10 | + | ||
| 11 | + | # 存取欄位值(像是屬性一樣) | |
| 12 | + | print(person1.name) # Timmy | |
| 13 | + | print(person1.age) # 30 | |
| 14 | + | print(person1.email) # timmy@example.com | |
| 15 | + | ||
| 16 | + | # NamedTuple 也是可被解包的(像一般 tuple) | |
| 17 | + | name, age, email = person1 | |
| 18 | + | print(f"{name} is {age} years old. Email: {email}") | |