程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python magic method (5):__ repr__ (self) method

編輯:Python

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 .

function

Definition object is repr() Behavior when a function or interactive interpreter is called , This method is generally oriented to programmers .

Parameters

self Represents the object itself .

Return value

Must be a string , Otherwise, throw an exception .

Example :

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 


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved