首页 > 编程语言 > 详细

python_面向对象——双下划线方法

时间:2019-12-08 22:18:20      阅读:88      评论:0      收藏:0      [点我收藏+]

1.__str__和__repe__

class Person(object):

    def __init__(self,name,age):
        self.name = name
        self.age = age

    def __str__(self):
        return stf:我叫{},今年{}岁.format(self.name,self.age)

    def __repr__(self):
        return repr:我叫{},今年{}岁.format(self.name, self.age)

p = Person(wdc,22)

print(repr(p))
print(str(p))
print(p)

技术分享图片

  str函数或者print函数调用时 = obj.__srt__()

  repr函数或者交互式解释器中调用时 = obj.__repr__()

  这两个方法的返回值必须是字符串,否则会抛出异常

class Person(object):

    def __init__(self,name,age):
        self.name = name
        self.age = age

    # def __str__(self):
    #     return ‘stf:我叫{},今年{}岁‘.format(self.name,self.age)

    def __repr__(self):
        return repr:我叫{},今年{}岁.format(self.name, self.age)

p = Person(wdc,22)

print(repr(p))
print(str(p))
print(p)

技术分享图片

 

 

 

 

   如果__str__没有被定义,那么就会使用__repr__来代替输出。

2.__del__析构方法

class Person(object):

    def __init__(self,name,age):
        self.name = name
        self.age = age

    def __del__(self):
        print(析构方法)

p = Person(wdc,22)

print(11111111111)
print(11111111111)
del p   #删除对象p
print(11111111111)
print(11111111111)

技术分享图片当对象再内存中被释放时,自动触发执行。

python_面向对象——双下划线方法

原文:https://www.cnblogs.com/wangdianchao/p/12007224.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!