本文介绍了我应该直接调用object .__ str __()吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用Python编写一个类,并且正在编写一个__str__()函数,以便我的print语句可以打印该类实例的字符串表示形式.有没有理由直接做这样的事情:

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__())

感觉因为还有其他更整洁的方法可以执行此操作,所以直接调用__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.

推荐答案

通常,dunder方法定义对象在特定上下文中的行为.它们不打算直接使用. (主要的例外是当您覆盖从父类继承的dunder方法时.)

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

对于__str__,有三种已记录的用法;内置函数strformatprint使用它,以便(大致而言)

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

这里的关键是__str__允许不是内置于Python的代码使用这些功能; __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.

这篇关于我应该直接调用object .__ str __()吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-09 18:32