zoukankan      html  css  js  c++  java
  • 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
  • 相关阅读:
    HDU1205 吃糖果【水题】
    HDU2568 前进【水题】
    架构图初体验
    五层架构
    文件系统权限设计涉及范畴
    微服务
    领域驱动设计
    容器技术Docker
    架构总结
    仓储模式的简单理解
  • 原文地址:https://www.cnblogs.com/yc3110/p/10443327.html
Copyright © 2011-2022 走看看