Jul-07-2023, 08:53 AM
Python has a rich data-model: https://docs.python.org/3/reference/data...-and-types
Some methods and attributes are created automatically.
For example, you can add the ability of comparison to your class and then all instances are sortable.
But after the creation of the class itself, it gets from
For example, the attribute
They implement those required methods with the decorator syntax.
The same as a
Some methods and attributes are created automatically.
For example, you can add the ability of comparison to your class and then all instances are sortable.
But after the creation of the class itself, it gets from
object
the attributes and methods assigned. For example, the attribute
__name__
holds the name of the class. But you have never created it, it's done automatically.from functools import total_ordering # adds additional methods to the class MyFoo # for comparison @total_ordering class MyFoo: def __init__(self, value): self.value = value def __eq__(self, other): print("__eq__ called") return self.value == other.value def __lt__(self, other): print("__lt__ called") return self.value < other.value def __repr__(self): return f"MyFoo: {self.value}" foos = [MyFoo(x) for x in range(10, -1, -1)] print(foos) foos.sort() print(foos)
Output:[MyFoo: 10, MyFoo: 9, MyFoo: 8, MyFoo: 7, MyFoo: 6, MyFoo: 5, MyFoo: 4, MyFoo: 3, MyFoo: 2, MyFoo: 1, MyFoo: 0]
__lt__ called
__lt__ called
__lt__ called
__lt__ called
__lt__ called
__lt__ called
__lt__ called
__lt__ called
__lt__ called
__lt__ called
[MyFoo: 0, MyFoo: 1, MyFoo: 2, MyFoo: 3, MyFoo: 4, MyFoo: 5, MyFoo: 6, MyFoo: 7, MyFoo: 8, MyFoo: 9, MyFoo: 10]
There is another way with the use of dataclass
.They implement those required methods with the decorator syntax.
The same as a
dataclass
.from dataclasses import dataclass @dataclass(order=True) class MyFoo2: value: int
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!