1. 程式人生 > >13 內建屬性 _getattribute_ 內建函數

13 內建屬性 _getattribute_ 內建函數

pytho pri main 就會 遞歸 class 運行 lan 代碼

1.內建屬性

技術分享圖片

2.__getattribute__ 屬性訪問時攔截器

class Itcast(object):
    def __init__(self,subject1):
        self.subject1 = subject1
        self.subject2 = cpp

    #屬性訪問時攔截器,打log
    def __getattribute__(self,obj):   #obj---->  subject
        if obj == subject1:
            print(log subject1)
            
return redirect python else: #測試時註釋掉這2行,將找不到subject2 return object.__getattribute__(self,obj) def show(self): print(this is Itcast) s = Itcast("python") print(s.subject1) print(s.subject2)
運行結果:


log subject1
redirect python
cpp

帶方法的

class Itcast(object):
    
def __init__(self,subject1): self.subject1 = subject1 self.subject2 = "cpp" #屬性訪問時攔截器,打log def __getattribute__(self,obj): print("====1>%s"%obj) if obj == "subject1": print("log subject1") return "redirect python" else: temp
= object.__getattribute__(self,obj) print("===2>%s"%str(temp)) return temp def show(self): print("thi si Itcast") s = Itcast("python") print(s.subject1) print(s.subject2) s.show()

====1>subject1
log subject1
redirect python
====1>subject2
===2>cpp
cpp
====1>show
===2><bound method Itcast.show of <__main__.Itcast object at 0x7efe2d627898>>
thi si Itcast

 

3 __getattribute__的坑

class Person(object):
        def __getattribute__(self,obj):
            print("---test---")
            if obj.startswith("a"):
                return "hahha"
            else:
                return self.test   
              #return object.__getattribute__(self,obj) #扔給父類給你處理
 

        def test(self):
            print("heihei")


    t.Person()

    t.a #返回hahha

    t.b #會讓程序死掉
        #原因是:當t.b執行時,會調用Person類中定義的__getattribute__方法,但是在這個方法的執行過程中
        #if條件不滿足,所以 程序執行else裏面的代碼,即return self.test  問題就在這,因為return 需要把
        #self.test的值返回,那麽首先要獲取self.test的值,因為self此時就是t這個對象,所以self.test就是
        #t.test 此時要獲取t這個對象的test屬性,那麽就會跳轉到__getattribute__方法去執行,即此時產
        #生了遞歸調用,由於這個遞歸過程中 沒有判斷什麽時候推出,所以這個程序會永無休止的運行下去,又因為
        #每次調用函數,就需要保存一些數據,那麽隨著調用的次數越來越多,最終內存吃光,所以程序 崩潰
        #
        # 註意:以後不要在__getattribute__方法中調用self.xxxx
        

4。內建函數

13 內建屬性 _getattribute_ 內建函數