PYTHON PROGRAMMING
Python classes have many faces. For instance, you can create an empty class:
class MyClass:
pass
and it still can be of use, for instance, as a sentinel value. You can add an __init__()
method:
class MyClass:
def __init__(self, value):
self.value = value
It still will be a very simple class, but this time, it’ll keep a particular value.
A superb power of Python classes is that they can be used as types, as shown below:
def foo(x: MyClass, n: int) -> list[MyClass]:
return [x] * n
Remember that not implementing the __init__()
method does not mean it doesn’t exist. In fact, we overloaded the __init__()
method above, not just implemented it. This is another significant aspect of Python classes that you should know: you can overload many other methods, such as __new__()
, __eq__()
, and __setattr__()
. If you do not overload these methods, some will have their default implementation (like __init__()
, __new__()
, __setattr__()
, and __eq__()
), while others will not (like __lt__()
and all the other comparison methods other than __eq__()
, __getitem__()
, __setitem__()
and __len__()
).
A class can inherit from another class, like here:
class MyClass(dict):
@staticmethod
def say_hello(self):
print("Hello!")
and, also as above, it can use static methods, but also class methods. You can create mixin classes and abstract base classes, singletons, and make tons of other things, sometimes very useful.
Python classes have so many faces that it would take years to discuss each of them in detail, and we’ll be doing so in the future articles. In this one, we will focus on one particular aspect: the difference between and the power of the __repr__()
and __str__()
methods.
At first glance, you may think this is a minor topic, but it’s actually quite important. It’s easy to implement a Python class, but it takes more effort to implement a good…