Python魔法函数

  python中定义的以__开头和结尾的的函数。可以随意定制类的特性。魔法函数定义好之后一般不需要我们自己去调用,而是解释器会自动帮我们调用。

  • __getitem__(self, item) 将类编程一个可迭代的对象。对象元素为item内的元素。
  • __len__(self,) 返回类的长度(如果没有改魔法函数就会报错)
  • __repr__(self)  定义类在开发模式调用时出来的内容
  • __str__(self) 定义print(类)出来的状态,即将类字符串化
  • __add__(self, other_instance) 将类与另一个类相加的时候调用。
  • __getattr__()调用类中一个不存在的属性时,就会启用该魔法方法。
  • __getattribute__()覆盖所有类的属性(其它类属性都失效),调用类的属性时,启动该魔法方法。
class MyVector():
    def __init__(self, x, y):
        self.x= x
        self.y= y

    def __add__(self, other_instance3):
        re_vector = MyVector(self.x + other_instance3.x, self.y+ other_instance3.y)
        return re_vector

    def __str__(self):
        return "x:{x}, y{y}".format(x=self.x, y = self.y)

class My_Vecotr_two():
    def __init__(self, x, y):
        self.x = x
        self.y = y
first_vecotr = MyVector(1, 2)
second_vector = My_Vecotr_two(2, 3)
print(first_vecotr+second_vector)

打印结果:
x:3, y5

 

posted @ 2019-02-27 14:05  脱离低级趣味  阅读(263)  评论(0编辑  收藏  举报