Introduction
Python is a scripting language. The base class of Python contains many methods like below.
In this article, we will try to override the one or two methods of Python, which are part of the base object. Usually, if we print an object in Python, it prints its object memory location value in Hexadecimal value. We will try to override that method that gives this value and write our custom string. The idea behind this override method is to understand that we can override the base object methods too and we can customize them if required.
Below is the Sample class.
class Sample():
print("All Good")
def message(self, msg):
return "Hello " + msg
sam = Sample()
print(sam)
text = sam.message("xyz")
print(text)
If we print Sam, now below is the output snap.
To override, we will override the __str__ method, so that we can return, and customize the value.
Below is the code.
class Sample():
print("All Good")
def message(self, msg):
return "Hello " + msg
def __str__(self) -> str:
return "Base method edited, This is Sample class"
sam = Sample()
print(sam)
text = sam.message("xyz")
print(text)
Below is the output snap.
The same thing can be achieved by overriding the __repr__ method.
Summary
I hope this article helps us to understand the overriding of basic objects in Python.