我看到当我尝试实例化一个类时,正在调用 __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/