Am So Mai 31 2020, 10:13:43 schrieb Hartmut Goebel:
Am 27.05.20 um 17:13 schrieb Peter Otten:
Die Reihenfolge kann durch die Positionierung in der Klasse bestimmt werden: Könnte man machen, allerdings würde ich mich nicht darauf verlassen, dass die Reihenfolge in `vars(A).keys()` immer stimmt. Kannst Du mit eine Doku dazu zeigen, ich habe nichts gefunden.
Was Knackiges kann ich auch nicht vorweisen, nur https://docs.python.org/3/whatsnew/3.6.html#pep-520-preserving-class-attribu... mit dem Verweis auf die PEP 520 – Preserving Class Attribute Definition Order https://www.python.org/dev/peps/pep-0520 bei deren Enstehung wohl noch nicht bekannt war, dass `dict`s die insertion order erhalten.
Allerdings hat mich Deine Mail noch auf einen ganz anderen Ansatz gebracht:
class A: _myprop = 1.23
@property def myprop(self): return self._myprop
@myprop.setter def myprop(self, value): if value < 2.5: self._myprop = value
a = A() print(a.myprop) a.myprop = 2.1 print(a.myprop)
Das hat den Vorteil, dass man sich nur auf Standard-Konstrukte verlässt. Für mutable defaults muss man das allerdings modifizieren.