魔术方法,使我们可以在面向对象的编程中做一些漂亮的技巧。这些方法由两个下划线(__)用作前缀和后缀。例如,充当拦截器,当满足某些条件时会自动调用它们。
在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'
现在将__add__方法添加到String类
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