__call__
object.__call__(self[, args...])
Called when the instance is “called” as a function; if this method is defined, x(arg1, arg2, ...) is a shorthand for x.__call__(arg1, arg2, ...).Python中有一個有趣的語法,只要定義類型的時候,實現__call__函數,這個類型就成為可調用的。換句話說,我們可以把這個類的對象當作函數來使用,相當于重載了括號運算符。
class Student(object):def __init__(self, name): self.name = name def __call__(self): print('My name is %s.' % self.name) s = Student('Michael') s() # My name is Michael.通過使用__setattr__,?__getattr__,?__delattr__可以重寫dict,使之通過“.”調用鍵值。
class Dict(dict):''' 通過使用__setattr__,__getattr__,__delattr__ 可以重寫dict,使之通過“.”調用 ''' def __setattr__(self, key, value): print("In '__setattr__") self[key] = value def __getattr__(self, key): try: print("In '__getattr__") return self[key] except KeyError as k: return None def __delattr__(self, key): try: del self[key] except KeyError as k: return None # __call__方法用于實例自身的調用,達到()調用的效果 def __call__(self, key): # 帶參數key的__call__方法 try: print("In '__call__'") return self[key] except KeyError as k: return "In '__call__' error" s = Dict() print(s.__dict__) # {} s.name = "hello" # 調用__setattr__ # In '__setattr__ print(s.__dict__) # 由于調用的'__setattr__', name屬性沒有加入實例屬性字典中。 # {} print(s("name")) # 調用__call__ # In '__call__' # hello print(s["name"]) # dict默認行為 # hello # print(s) print(s.name) # 調用__getattr__ # In '__getattr__ # hello del s.name # 調用__delattr__ print(s("name")) # 調用__call__ # None轉載于:https://www.cnblogs.com/saolv/p/9839523.html
與50位技術專家面對面20年技術見證,附贈技術全景圖總結
- 上一篇: 沐川的湿气太重了
- 下一篇: 厨房推拉门是靠里还是靠外装好?谢啦!