Dup Ver Goto 📝

Casting to Int and Float

PT2/lang/python/classes python does not exist
To
33 lines, 92 words, 677 chars Page 'CastToIntFloat' does not exist.

Three relatively unknown __dunder__ methods, __int__ and __float__, and __bool__ define the result of casting to int, float, and bool respectively

class A:
  def __int__(self):
    return 42
  def __float__(self):
    return 3.14159
  def __bool__(self):
    return True

a = A()
print(int(a))
# 42
print(float(a))
# 3.14159
print(bool(a))
# True

Dict and List

As for dict and list, these rely in using an iterator obtained via the __iter__ method:

class A:
  def __iter__(self):
    return iter([("pi",3.14159),("answer",42)])

a = A()
print(dict(a))
# {'pi': 3.14159, 'answer': 42}
print(list(a))
# [('pi', 3.14159), ('answer', 42)]