I'm writing a class in Python and I'm writing a __str__()
function so my print statements can print string representations of instances of that class. Is there ever a reason to directly do something like this:
myObj = Foo(params)
doSomething(myObj.__str__())
It feels like since there are other neater ways to do this, it would be a bad idea (or at least, not proper style) to directly call __str__()
. That said, I can't find a website specifically saying not to.
Short answer: Yes! Called by str(object) and the built-in functions format() and print() to compute the “informal” or nicely printable string representation of an object.
If we have not defined the __str__ , then it will call the __repr__ method.
__del__ is a destructor method which is called as soon as all references of the object are deleted i.e when an object is garbage collected. Syntax: def __del__(self): body of destructor . .
The __call__ method enables Python programmers to write classes where the instances behave like functions and can be called like a function. When the instance is called as a function; if this method is defined, x(arg1, arg2, ...) is a shorthand for x. __call__(arg1, arg2, ...) .
In general, dunder methods define how an object behaves in a particular context. They aren't intended to be used directly. (The major exception being when you are overriding a dunder method inherited from a parent class.)
In the case of __str__
, there are three documented uses; it is used by the built-in functions str
, format
, and print
so that (roughly speaking)
str(myObj) == myObj.__str__()
format("{}", myObj) == format("{}", myObj.__str__())
print(myObj) == print(myObj.__str__())
.The key here is that __str__
allows code that isn't built-in to Python to work with these functions; the __str__
method provides the common interface all three can use.
myObj.__str__()
is the same as
str(myObj)
unless someone has the bad idea to hide str
built-in by reassigning its name:
str = lambda x: None
in which case only the first approach would work. But in the general case, it's better to avoid calling those dunder methods directly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With