تقنية

total_ordering في بايثون: هل تستبدل __le__ الموروثة؟

total_ordering; Child(Parent); own __lt__/__eq__; Child.__le__ is Parent.__le__:True; Child(4)<=Child(5):RuntimeError; calls=["base"]
طريقة محفوظة.

لا؛ total_ordering تحفظ __le__ الموروثة في مثالنا، حتى مع __lt__ و__eq__ مكتوبتين. [1] [2]

الخلاصة السريعة

لا تستبدلها هنا. [1] [2]

  • لا؛ total_ordering تحفظ __le__ الموروثة في مثالنا، حتى مع __lt__ و__eq__ مكتوبتين. [1] [2]
  • في CPython 3.12.14، Parent.__le__ تسجل base وترفع RuntimeError؛ Child ترثها وتعرف __lt__/__eq__ للأعداد. [1] [2]
  • Child.__le__ is Parent.__le__ تعطي True؛ left<right تعطي True، لكن left<=right ترفع RuntimeError وcalls=["base"]. [1] [2]
  • المزخرف يملأ الناقص؛ لا يستبدل الطريقة المعرّفة في فئة أصلية. نجاح تعريف Child لا يصلح طريقتها الموروثة. [1] [2]
  • تحكم: Fixed دون Parent تطبق المزخرف بمقارنات القيم نفسها؛ Fixed(4)<=Fixed(5) تعطي True بالطريقة المولدة. لا نختبر أنواعًا مختلفة أو أصنافًا مجردة. [1] [2]

الحفظ

لا؛ total_ordering تحفظ __le__ الموروثة في مثالنا، حتى مع __lt__ و__eq__ مكتوبتين. [1] [2]

فئة أصلية

في CPython 3.12.14، Parent.__le__ تسجل base وترفع RuntimeError؛ Child ترثها وتعرف __lt__/__eq__ للأعداد. [1] [2]

الطريقة الموروثة

Child.__le__ is Parent.__le__ تعطي True؛ left<right تعطي True، لكن left<=right ترفع RuntimeError وcalls=["base"]. [1] [2]

from functools import total_ordering calls=[] class Parent: def __le__(self,other): calls.append("base");raise RuntimeError("bud") @total_ordering class Child(Parent): def __init__(self,n):self.n=n def __lt__(self,other):return self.n<other.n def __eq__(self,other):return self.n==other.n left,right=Child(4),Child(5) print(Child.__le__ is Parent.__le__,left<right) try:left<=right except RuntimeError:print("RuntimeError",calls) [1] [2]

total_ordering; Fixed; own __lt__/__eq__; no Parent; n=4,5; Fixed(4)<=Fixed(5):True
مقارنة مولدة.

التوليد والتحكم

المزخرف يملأ الناقص؛ لا يستبدل الطريقة المعرّفة في فئة أصلية. نجاح تعريف Child لا يصلح طريقتها الموروثة. [1] [2]

@total_ordering class Fixed: def __init__(self,n):self.n=n def __lt__(self,other):return self.n<other.n def __eq__(self,other):return self.n==other.n print(Fixed(4)<=Fixed(5)) [1] [2]

تحكم: Fixed دون Parent تطبق المزخرف بمقارنات القيم نفسها؛ Fixed(4)<=Fixed(5) تعطي True بالطريقة المولدة. لا نختبر أنواعًا مختلفة أو أصنافًا مجردة. [1] [2]

المراجع

  1. Python total_ordering
  2. CPython functools

للتوسع: لغات البرمجة.

أُعدّ هذا المقال بمساعدة الذكاء الاصطناعي، وخضع لمراجعة ذاتية بالأداة نفسها. لا يُنسب إلى مراجع بشري أو خبير مستقل. منهجية المحتوى.