Python There are some magical ways to do it , They are always surrounded by double underscores , They are object-oriented Of Python Everything . They are special ways to add magic to your classes , If your object implements ( heavy load ) A magic method , Then this method will be automatically used in special cases Python The call .
Definition object is repr() Behavior when a function or interactive interpreter is called , This method is generally oriented to programmers .
self Represents the object itself .
Must be a string , Otherwise, throw an exception .
class MyText:
def __repr__(self) -> str:
return 'My is repr'
sample = MyText()
# My is repr
print(sample)
# My is repr
print(repr(sample))
result :
My is repr
My is repr
__repr__()
yes Python A special method in class , from object The object provides , Because all classes are object Class Subclass , So all classes will inherit this method .
The main implementation of this method “ Self description ” function —— When printing instantiated objects of a class directly , The system will automatically call this method , Output self description information of the object , It is used to tell the external object the state information it has .
however ,object Class provides the __repr__()
Method always returns an object ( Class name + obejct at + Memory Address ), This value does not really realize the function of self description ! as follows :
class Person():
def __init__(self, name, age):
self.name = name
self.age = age
person = Person('zk', 20)
print(person)
print(person.__repr__())
Execution results :
<__main__.Person object at 0x0000020F6A467B20>
<__main__.Person object at 0x0000020F6A467B20>
therefore , If you want to implement “ Self description ” The function of , So you have to rewrite repr Method :
class Person():
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return 'Person class , Yes name and age Two attributes '
person = Person('zk', 20)
print(person)
print(person.__repr__())
Execution results :
Person class , Yes name and age Two attributes
Person class , Yes name and age Two attributes
The main knowledge points are
Want to write your own experie