python 中的丹迪爾或魔術方法
這些魔術方法讓我們可以在面向物件的程式設計中做一些很酷的事情。使用兩個下劃線 (__) 作為字首和字尾來標識這些方法。例如,當滿足某些條件時會自動呼叫的攔截器函式。
在 python 中 __repr__ 是用來計算物件的“正式”字串表示形式的內建函式,而 __str__ 是用來計算物件的“非正式”字串表示形式的內建函式。
示例程式碼
class String: # magic method to initiate object def __init__(self, string): self.string = string # Driver Code if __name__ == '__main__': # object creation my_string = String('Python') # print object location print(my_string)
輸出
<__main__.String object at 0x000000BF0D411908>
示例程式碼
class String: # magic method to initiate object def __init__(self, string): self.string = string # print our string object def __repr__(self): return 'Object: {}'.format(self.string) # Driver Code if __name__ == '__main__': # object creation my_string = String('Python') # print object location print(my_string)
輸出
Object: Python
我們嘗試向其中新增一個字串。
示例程式碼
class String: # magic method to initiate object def __init__(self, string): self.string = string # print our string object def __repr__(self): return 'Object: {}'.format(self.string) # Driver Code if __name__ == '__main__': # object creation my_string = String('Python') # concatenate String object and a string print(my_string + ' Program')
輸出
TypeError: unsupported operand type(s) for +: 'String' and 'str'
現在向 String 類新增 __add__ 方法
示例程式碼
class String: # magic method to initiate object def __init__(self, string): self.string = string # print our string object def __repr__(self): return 'Object: {}'.format(self.string) def __add__(self, other): return self.string + other # Driver Code if __name__ == '__main__': # object creation my_string = String('Hello') # concatenate String object and a string print(my_string +' Python')
輸出
Hello Python
廣告