我看到当我尝试实例化一个类时,正在调用__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
>>>
答案 0 :(得分:3)
以下是创建类实例时调用__str__()
的原因:
def __init__(self):
print self
^^^^^^^^^^ THIS
这里,Python需要打印对象。为此,它将对象转换为字符串(通过调用__str__()
)并打印出结果字符串。
最重要的是,您在第二个示例中看到了__repr__()
,因为交互式shell尝试打印出A()
的结果。