iT邦幫忙

第 11 屆 iThome 鐵人賽

DAY 29
0
自我挑戰組

Why it works: python requests and urllib3系列 第 29

Day29-python-class-Special method names

  • 分享至 

  • xImage
  •  

Day25-CaseInsensitiveDict出現了很多被雙底線包圍的方法,這些特別的方法可以針對語言層級的運算子定義並客製化自己的行為,舉例來說,CaseInsensitiveDict定義了__getitem__()方法,若x為CaseInsensitiveDict的物件,亦即重新定義了x[key]所產生的行為

This is Python’s approach to operator overloading, allowing classes to define their own behavior with respect to language operators

和物件生命週期有關

  • __new__
  • __init__
  • __del__

__new__和__init__須互相配合才能創造並初始化一個物件,較常使用的應該是__init__

Use __new__ when you need to control the creation of a new instance.
Use __init__ when you need to control initialization of a new instance.

相較於物件的生成,物件的回收需透過__del__,常被稱為finalizer或是destructor

題外話,del xx.__del__()在行為上有些差異

del x doesn’t directly call x.del() — the former decrements the reference count for x by one, and the latter is only called when x’s reference count reaches zero.

表達物件

  • __repr__
    • Called by the repr() built-in function
    • the official string representation of an object
    • this should look like a valid Python expression
    • This is typically used for debugging, so it is important that the representation is information-rich and unambiguous.
  • __str__
    • Called by str(object) and the built-in functions format() and print()
    • the informal or nicely printable string representation of an object
  • __format__
    • Called by the format() built-in function, and by extension, evaluation of formatted string literals and the str.format() method
    • the formatted string representation of an object

至少需要實現__repr__

在model.py中PreparedRequest定義如下

    def __repr__(self):
        return '<PreparedRequest [%s]>' % (self.method)

模擬callable objects

  • __call__
    • Called when the instance is called as a function

模擬container types

Containers usually are sequences (such as lists or tuples) or mappings (like dictionaries), but can represent other containers as well

模擬context managers

A context manager is an object that defines the runtime context to be established when executing a with statement.
The context manager handles the entry into, and the exit from, the desired runtime context for the execution of the block of code.

  • __enter__
  • __exit__

參考


上一篇
Day28-text-binary-encoding
下一篇
Day30-紙上得來終覺淺,絕知此事要躬行
系列文
Why it works: python requests and urllib330
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言