面向對象高階-05__str__和__repr__和\_\_format\_\_

__str__

會在對象被轉換爲字符串時或print()時候,轉換的結果就是這個函數的返回值
使用場景:咱們能夠利用該函數來自定義,對象的是返回值(通常人爲爲打印格式)
列子一python

class Foo:
    def __init__(self, name, age):
        """對象實例化的時候自動觸發"""
        self.name = name
        self.age = age

    def __str__(self):
        print('打印的時候自動觸發,可是其實不須要print便可打印')
        return f'{self.name}:{self.age}'  # 若是不返回字符串類型,則會報錯

obj = Foo('nash', 18)
print(obj)  # obj.__str__() # 打印的時候就是在打印返回值

列子二程序員

import time
class  Person:

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

    def __str__(self):

        return "這是一個person對象 name:%s age:%s" % (self.name,self.age)
    pass

    def __del__(self):
        print("del run")


p = Person("jack",20)

# del p

time.sleep(2)
# 備註下 str 也會調用__str__ 哦!!!!!
str(p)
print("over")

# 輸出結果
# over
# del run




__repr__

str函數或者print函數--->obj.__str__()
repr或者交互式解釋器--->obj.__repr__()
若是__str__沒有被定義,那麼就會使用__repr__來代替輸出
注意:這倆方法的返回值必須是字符串,不然拋出異常函數

class School:
    def __init__(self, name, addr, type):
        self.name = name
        self.addr = addr
        self.type = type

    def __repr__(self):
        return 'School(%s,%s)' % (self.name, self.addr)

    def __str__(self):
        return '(%s,%s)' % (self.name, self.addr)


s1 = School('oldboy1', '北京', '私立')
print('from repr: ', repr(s1))
# 輸出結果
# from repr:  School(oldboy1,北京)

print('from str: ', str(s1))
# 輸出結果
# from str:  (oldboy1,北京)

print(s1)
# 輸出結果
# (oldboy1,北京)

s1  # jupyter屬於交互式
# 輸出結果
# School(oldboy1,北京)




__format__

__format__ 方法能夠用來我的呢根據已有格式來定製輸出格式,不太經常使用(我的以爲了解便可)code

date_dic={
    'ymd':'{0.year}:{0.month}:{0.day}',
    'dmy':'{0.day}/{0.month}/{0.year}',
    'mdy':'{0.month}-{0.day}-{0.year}',
}
class Date:
    def __init__(self,year,month,day):
        self.year=year
        self.month=month
        self.day=day

    def __format__(self, format_spec):
        if not format_spec or format_spec not in date_dic:
            format_spec='ymd'
        fmt=date_dic[format_spec]
        return fmt.format(self)

d1=Date(2016,12,29)
print(format(d1))
print('{:mdy}'.format(d1))

輸出結果:
2016:12:29
12-29-2016orm

我的總結:
二者區別嘛都上上面各自特色啦~~~
通常都只會用到一種咯,那就是 __str__
__str__ 更可能是給用戶者的,而 _\repr__ 更多的是提供給程序員的
__format__ 也能夠直接format調用,但不少時候都只是裝飾數據做用,不太經常使用
對此有些時候 能夠用 __repr__ = __str__ 意思爲把__repr__指向__str__方法, 對 你猜的沒錯,這二者就同樣啦,都爲__str__方法,避免了方法重複意外出錯對象

相關文章
相關標籤/搜索