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