python - __str__ 和 __repr__ 在实例化期间被调用

标签 python

我看到当我尝试实例化一个类时,正在调用 __str____repr__ 。我在很多文档中看到在打印操作期间调用 __str__ 以及类似于 __str____repr__ 函数。我看到当我尝试创建一个对象时,这些方法被调用。有人能让我明白发生了什么吗?

class A:
    print "You are in Class A"
    #The init method is a special method used when instantiating a class
    #Python looks for this function if its present in the class the arguments passed during the   instantiation of a class
    #is based on the arguments defined in this method. The __init__ method is executed during instantiation

    def __init__(self):
        print self
        print "You aer inside init"

    #Once the instance of a class is created its called an object. If you want to call an object like a method
    #say x=A() here x is the object and A is the class
    #Now you would want to call x() like a method then __call__ method must be defined in that class
    def __call__(self):
        print "You are inside call"

    #The __str__ is called when we use the print function on the instance of the class
    #say x=A() where x is the instance of A. When we use print x then __str__ function will be called
    #if there is no __str__ method defined in the user defined class then by default it will print
    #the class it belongs to and also the memory address
    def __str__(self):
        print "You are in str"
        return "You are inside str"

    #The __repr__ is called when we try to see the contents of the object
    #say x=A() where x is the instance of the A. When we use x it prints a value in the interpreter
    #this value is the one returned by __repr__ method defined in the user-defined class
    def __repr__(self):
        print "You are in repr"
        return "This is obj of A"

class B:
    print "You are in Class B"

epradne@eussjlx8001:/home/epradne>python -i classes.py
You are in Class A
You are in Class B
>>> a=A() <-------- I create the object a here
You are in str <------- Why is __str__ method executed here??
You are inside str
You aer inside init
>>> A() <------------- I just call the class and see both __str__ and __repr__ are being executed
You are in str   
You are inside str
You aer inside init
You are in repr
This is obj of A
>>>                      

最佳答案

原因如下__str__()当您创建类的实例时调用:

def __init__(self):
    print self
    ^^^^^^^^^^ THIS

这里,Python需要打印该对象。为此,它将对象转换为字符串(通过调用 __str__() )并打印出结果字符串。

最重要的是,您会看到 __repr__()在第二个示例中调用是因为交互式 shell 尝试打印 A() 的结果.

关于python - __str__ 和 __repr__ 在实例化期间被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26577009/

相关文章:

python - (有)python socketserver 相对于常规套接字对象的性能优势吗?

python - 如何在 O(n) 的列表中找到另一个总和为目标数的整数?

PythonAnywhere 脚本调度程序不工作

python - 将 win32lfn 扩展与 Mercurial 捆绑在一起

python - python中的异步等待/非阻塞等待

python - 使用 scikit-learn 绘制接收器操作特性时出现问题?

python - pandas - 将两个数据框放入一列

具有动态主机/服务器的 python 结构

python - 在单元测试中哪里捕获键盘中断?

python - 初始化由字符和数字组成的字典的最优雅方法是什么