编程语言
首页 > 编程语言> > python魔术方法

python魔术方法

作者:互联网

  魔术方法

 

  魔法方法(Magic Method)是python内置方法,格式为:"__方法名__",不需要主动调用,存在的目的是为了给python的解释器进行调用,几乎每个魔法方法都有一个对应的内置函数,或者运算符,当我们对这个对象使用这些函数或者运算符时就会调用类中的对应魔法方法,可以理解为重写这些python的内置函数。

#当你直接定义
a=(1,2)
b=(2,3)
c=a+b
print(c)    #输出结果为(1,2,2,3)

   

#魔术方法
class Method:   #定义一个类
    def __init__(self,a,b):     #构造器,当一个实例被创建的时候调用的初始化方法
        self.a=a
        self.b=b

    def __add__(self, other):   #定义加法的行为:+
        return (self.a+other.a,self.b+other.b)

a=Method(1,2)
b=Method(2,3)
c=a+b
# d=a-b    我们没有写def __sub__ 所以这个会报错
print(c)  输入为(3,5)
# print(d)

  我们可以再写一个 def __sub__(self,other):

            return (self.a-self.b,other.a-other.b)

  这样上面的注释就可以取消了  print(d)  输出为(-1,-1)

  我们再看一个关于魔术方法

class City:
    def __init__(self,name,pop):
        self.name=name
        self.pop=pop

    def __add__(self, other):
        new_name=self.name+other.name
        new_pop=self.pop+other.pop
        return City(new_name,new_pop)

    def __str__(self):
        return f'{self.name}:{self.pop}'


city1=City("上海市",1000)
city2=City("深圳市",1800)
city3=city1+city2
print(city3)  #输出为 上海市深圳市:2800
#如果上面没有写def __str__函数返回的就是地址 <__main__.City object at 0x000002C073D53B50>

  我们可以通过dir(int)来查看int类的魔术方法有那些

  ['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__', '__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__', '__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'as_integer_ratio', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']

  dir(str)的魔术方法

  ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

  详细的魔术方法请看文档

标签:__,name,python,self,pop,魔术,other,方法,def
来源: https://www.cnblogs.com/AIynzy/p/15080643.html