#!/usr/bin/python3 # ==================================================================== # from: www.youtube.com/watch?v=y1ZWQQEe5PM # 5 Useful Dunder Methods In Python # ==================================================================== from typing import Self # ---- class definition ---------------------------------------------- class TestFruit: def __int__(self,*,name='Tom'): self.name = name # ---- class definition ---------------------------------------------- class Fruit: # ---- note: * forces name/value pairs to follow def __init__(self, *, name: str, grams: float) -> None: self.name = name self.grams = grams # ---- Note: the default method only compairs IDs # ---- this compairs the values in objects of the same class def __eq__(self, other: Self) -> bool: ## to compare the name values ## return self.name == other.name ## compare everything (i.e. names, grams, ...) ## print(self.__dict__) ## print(other.__dict__) return self.__dict__ == other.__dict__ # ---- main ---------------------------------------------------------- def main() -> None: f1: Fruit = Fruit(name="Apple",grams=100) f2: Fruit = Fruit(name="Orange",grams=150) f3: Fruit = Fruit(name="Apple",grams=100) # ---- note: f1 equals f3, f1 does not equal f2 print(f1 == f2) print(f1 == f3) # -------------------------------------------------------------------- # ---- main # -------------------------------------------------------------------- if __name__ == '__main__': main()