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

更新於: 30-Jul-2019

434 次瀏覽

開啟你的 職業

完成課程獲得認證

立即開始
廣告