python特殊函数__str__、__repr__和__len__

时间:2021-12-08 18:56:08

1.__str__

首先介绍__str__

class Students(object):
def __init__(self, *args):
self.names = args # def __str__(self):
#   return str(self.names)
# __repr__ = __str__
ss = Students('hyq','ysy')
ss >>><__main__.Students at 0x2075a779828>

打印类对象显示的是对象的内存地址,下面重构__repr__和__str__方法

再看:

class Students(object):
def __init__(self, *args):
self.names = argsdef __str__(self):
return str(self.names)
# def __repr__(self):
# return str(self.names)
ss = Students('hyq','ysy')
ss >>><__main__.Students at 0x2075a78a860>
class Students(object):
def __init__(self, *args):
self.names = args # def __str__(self):
# return str(self.names)
def __repr__(self):
return str(self.names)
ss = Students('hyq','ysy')
ss >>>('hyq', 'ysy')

可以看到,重构__repr__方法后,直接输出对象,能够按照__repr__中定义的格式进行显示;

而重构__str__方法后,直接输出对象,显示的是对象的内存地址,并不是__str__定义的格式

当然,用print都能够显示__repr__和__str__定义的格式

class Students(object):
def __init__(self, *args):
self.names = args # def __str__(self):
#   return str(self.names)
def __repr__(self):
return str(self.names)
ss = Students('hyq','ysy')
print(ss) >>>('hyq','ysy') ————————————————————————————————————————————分割线————————————————————————————————————
class Students(object):
def __init__(self, *args):
self.names = argsdef __str__(self):
return str(self.names)
# def __repr__(self):
# return str(self.names)
ss = Students('hyq','ysy')
print(ss) >>>('hyq','ysy')

注意:

在代码中一般写成:

def __str__(self):
return str(self.names)
__repr__ = __str__

2.__len__

如果一个类表现得像一个list,要获取有多少元素,就得用len()函数

要让len()函数正常工作,类必须提供一个特殊方法__len__(),返回元素的个数

class Students(object):
def __init__(self, *args):
self.names = args
def __len__(self):
return len(self.names) ss = Students('hyq','ysy')
print(len(ss) >>>2