The Extra Methods Your Python Class Needs!
Python has some beautiful things builtin to their classes. You’ll never see them half the time, but if you implement them they’re pretty cool.
The most important one to implement is the “__str__” method. This gives a custom string representation to the class. It’s super useful! If you’re debugging and you want to know what’s going on in the class it’s perfect.
class magic(object):
def __init__(self, item):
# Initialise the class
self.item = item def __str__(self):
# String rep of the class
return self.itemnew = magic('thing')
print( new ) #output is "thing"
In Python functions are first-class objects. This means that they can be passed to functions and methods just as if they were objects of any other kind. Calling “__call__” allows instances of your classes to behave as if they were functions. This is super common with decorators (checkout my article about decorators for an example).
class magic(object):
def __init__(self, item):
# Initialise the class
self.item = item def __call__(self):
# Call the class as a method
self.item = 2*self.itemnew = magic(10)
new() # Call class as a function
print( new.item ) # Item is now 20
“__del__” Is another important method to know about, it doesn’t need to be overwritten all the time. It’s called when an instance is about to be destroyed. This is also called a destructor. If a base class has a “__del__()” method, the derived class’s “__del__()” method must explicitly call it to ensure proper deletion of the base class part of the instance. This is particularly important if there are linked objects, it’s good to be explicit about that kinda thing.
class magic(object):
def __init__(self, item):
# Initialise the class
self.item = item def __del__(self):
# Call the class as a method
print( "Deleted", self.item)new = magic("This Item")
del new # prints "Deleted This Item"