1. 程式人生 > >七夕節寫那些結伴而行的特殊方法

七夕節寫那些結伴而行的特殊方法

getattr format 切片 pre step value mat 序列 art

__getattr__和__setattr__

這兩個特別簡單,__getattr__是通過屬性操作符.或者反射getattr(),hasattr()無法獲取到指定屬性(對象,類,父類)的時候,該方法被調用

__setattr__則是設置屬性的時候被調用

class A:
    def __getattr__(self, item):

        print(‘%s找不到這個屬性‘%item)

    def __setattr__(self, instance, value):
        print(‘設置了%s == %s‘%(instance,value))

a = A()
a.aa # aa找不到這個屬性
hasattr(a,‘bb‘) # bb找不到這個屬性

a.aa = ‘a‘ # 設置了aa == a
setattr(a,‘bb‘,‘bb‘) # 設置了bb == bb

與他相關的一個方法__getattribute__,嘗試獲取屬性時總會調用這個方法(特殊屬性或特殊方法除外),當該方法拋出AttributeError時才會調用__getattr__方法.

class A:
    def __getattr__(self, item):

        print(‘%s找不到這個屬性‘%item)

    def __setattr__(self, instance, value):
        print(‘設置了%s == %s‘%(instance,value))
    def __getattribute__(self, item):
        return 1
a = A()
print(a.aa) # 1
print(hasattr(a,‘bb‘)) #True

a.aa = ‘a‘ # 設置了aa == a
setattr(a,‘bb‘,‘bb‘) # 設置了bb == bb

__getitem__和__setitem__

對象使用[]時調用的方法, 這裏主要說一下切片的原理.

關鍵字存在一個slice(), 其實這是一個類

print(slice) # <class ‘slice‘>

print(dir(slice))
# [‘__class__‘, ‘__delattr__‘, ‘__dir__‘, ‘__doc__‘, ‘__eq__‘, ‘__format__‘, ‘__ge__‘, 
# ‘__getattribute__‘, ‘__gt__‘, ‘__hash__‘, ‘__init__‘, ‘__init_subclass__‘, ‘__le__‘, ‘__lt__‘, 
# ‘__ne__‘, ‘__new__‘, ‘__reduce__‘, ‘__reduce_ex__‘, ‘__repr__‘, ‘__setattr__‘, ‘__sizeof__‘, 
# ‘__str__‘, ‘__subclasshook__‘, ‘indices‘, ‘start‘, ‘step‘, ‘stop‘]

  其中indices方法可以根據序列長度修改切片信息,返回一個由起始位置,結束位置,步幅組成的元組.

print(slice(0,10,2).indices(6)) # (0, 6, 2)
print(slice(-3).indices(6)) # (0, 3, 1)

  

七夕節寫那些結伴而行的特殊方法