dataclass_person_example.py
· 250 B · Python
Bruto
from dataclasses import dataclass
@dataclass
class Person:
name: str
age: int
email: str
# 建立實例
person1 = Person(name="Timmy", age=30, email="timmy@example.com")
# 修改值也可以(可變)
person1.age = 31
print(person1)
| 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) |
| 15 |
named_tuple_person_example.py
· 459 B · Python
Bruto
from typing import NamedTuple
class Person(NamedTuple):
name: str
age: int
email: str
# 建立實例
person1 = Person(name="Timmy", age=30, email="timmy@example.com")
# 存取欄位值(像是屬性一樣)
print(person1.name) # Timmy
print(person1.age) # 30
print(person1.email) # timmy@example.com
# NamedTuple 也是可被解包的(像一般 tuple)
name, age, email = person1
print(f"{name} is {age} years old. Email: {email}")
| 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}") |
| 19 |