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
廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP