กรณีสำหรับ StrEnum ใน Python 3.11
Dec 21 2022
ด้วยการอัปเดตเป็น Python 3.11 เราพบกับการเปลี่ยนแปลงเล็กน้อยในพฤติกรรมของ Enum
ด้วยการอัปเดตเป็น Python 3.11 เราพบกับการเปลี่ยนแปลงเล็กน้อยในพฤติกรรมของ Enum ต้องขอบคุณ PEP 663 — Standardizing Enum str(), repr () and format() behaviors
ก่อน Python 3.11
ก่อน Python 3.11 สตริง enum ดังที่แสดงด้านล่างจะส่งคืนค่าของรายการใน enum เมื่อใช้ผ่านรูปแบบหรือ f-string แต่ไม่ใช่เมื่อเรียกใช้โดย__str__()ปริยาย
# Python 3.10
from enum import Enum
class Foo(str, Enum):
BAR = "bar"
x = Foo.BAR
x # Outputs <Foo.BAR: 'bar'>
f"{x}" # Outputs 'bar'
"{}".format(x) # Outputs 'bar'
str(x) # Outputs 'Foo.BAR'
x.value # Outputs 'bar'Python 3.11
# Python 3.11
from enum import Enum
class Foo(str, Enum):
BAR = "bar"
x = Foo.BAR
x # Outputs <Foo.BAR: 'bar'>
f"{x}" # Outputs 'Foo.BAR'
"{}".format(x) # Outputs 'Foo.BAR'
str(x) # Outputs 'Foo.BAR'
x.value # Outputs 'bar'
ใน Python 3.11 StrEnumถูกเพิ่มเข้าไปในไลบรารีมาตรฐาน การใช้สิ่งนั้นแทนรูปแบบดังกล่าวของ enums ทำให้พฤติกรรมชัดเจนยิ่งขึ้น
# Python 3.11
from enum import StrEnum, auto
class Foo(StrEnum):
BAR = auto()
x = Foo.BAR
x # Outputs <Foo.BAR: 'bar'>
f"{x}" # Outputs 'bar'
"{}".format(x) # Outputs 'bar'
str(x) # Outputs 'bar'
x.value # Outputs 'bar'





































![รายการที่เชื่อมโยงคืออะไร? [ส่วนที่ 1]](https://post.nghiatu.com/assets/images/m/max/724/1*Xokk6XOjWyIGCBujkJsCzQ.jpeg)