实例化时调用__str__和__repr__
我注意到,当我尝试创建一个类的实例时,__str__
和 __repr__
这两个方法会被调用。我在很多文档中看到,__str__
是在打印操作时被调用的,而 __repr__
的功能和 __str__
类似。我发现当我尝试创建一个对象时,这些方法也会被调用。有人能帮我理解这是怎么回事吗?
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
>>>
1 个回答
3
下面是为什么在你创建一个类的实例时会调用 __str__()
的原因:
def __init__(self):
print self
^^^^^^^^^^ THIS
这里,Python 需要打印这个对象。为了做到这一点,它会把这个对象转换成字符串(通过调用 __str__()
),然后打印出这个字符串。
另外,你会看到在第二个例子中调用了 __repr__()
,因为交互式命令行想要打印出 A()
的结果。