Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I ever directly call object.__str__()?

Tags:

python

oop

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.

like image 737
Ben Cooper Avatar asked Apr 06 '18 15:04

Ben Cooper


People also ask

Can you directly call the __ str __ method?

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.

Which method will execute if __ str __ method is not available?

If we have not defined the __str__ , then it will call the __repr__ method.

What is __ del __ in Python?

__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 . .

What is the __ call __ method?

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, ...) .


Video Answer


2 Answers

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)

  1. str(myObj) == myObj.__str__()
  2. format("{}", myObj) == format("{}", myObj.__str__())
  3. 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.

like image 189
chepner Avatar answered Oct 23 '22 07:10

chepner


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.

like image 24
Jean-François Fabre Avatar answered Oct 23 '22 06:10

Jean-François Fabre