# string representationclass Point: def __init__(self, x, y): self.x = x self.y = y def __str__(self): return f"Point({self.x}, {self.y})"str(Point(3, 4))#ans: "Point(3, 4)"print(Point(3, 4))#ans: Point(3, 4)
# len() supportclass MyList: def __init__(self, items): self.items = items def __len__(self): return len(self.items)len(MyList([1, 2, 3]))#ans: 3
# indexing supportclass MyList: def __init__(self): self.items = [] def __getitem__(self, index): return self.items[index] def __setitem__(self, index, value): self.items[index] = valueml = MyList()ml.items = [1, 2, 3]ml[0]#ans: 1
# operator overloadingclass Vector: def __init__(self, x): self.x = x def __add__(self, other): return Vector(self.x + other.x)Vector(5) + Vector(3)#ans: Vector(8)
# comparison operatorsclass Point: def __init__(self, x): self.x = x def __eq__(self, other): return self.x == other.x def __lt__(self, other): return self.x < other.xPoint(5) == Point(5)#ans: True
# __str__ vs __repr__?class MyClass: def __str__(self): return "str" def __repr__(self): return "repr"str(MyClass())#ans: "str"repr(MyClass())#ans: "repr"
# __len__ return type?class MyClass: def __len__(self): return 5.5len(MyClass())#ans: TypeError (must return int)
# __getitem__ for iteration?class MyClass: def __getitem__(self, i): if i >= 3: raise IndexError return ifor x in MyClass(): print(x)#ans: 0, 1, 2
# __add__ with int?class MyClass: def __init__(self, x): self.x = x def __add__(self, other): return MyClass(self.x + other)MyClass(5) + 3#ans: MyClass(8)
# __contains__?class MySet: def __init__(self, items): self.items = set(items) def __contains__(self, item): return item in self.items2 in MySet([1, 2, 3])#ans: True
# __call__?class Multiplier: def __init__(self, n): self.n = n def __call__(self, x): return x * self.ndouble = Multiplier(2)double(5)#ans: 10
# __bool__?class MyClass: def __bool__(self): return Falsebool(MyClass())#ans: False
# __iter__?class MyRange: def __init__(self, n): self.n = n def __iter__(self): return iter(range(self.n))list(MyRange(3))#ans: [0, 1, 2]
# __enter__ and __exit__?class MyContext: def __enter__(self): return self def __exit__(self, *args): passwith MyContext() as ctx: pass
# __del__?class MyClass: def __del__(self): print("Deleted")obj = MyClass()del obj#ans: "Deleted"
Google tag (gtag.js)