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
  • 相关阅读:
    Ubuntu:替换DASH图标
    使用 python 操作 mongodb 常用的操作
    boost Asio网络编程简介
    optional的使用
    boost中Function和Lambda的使用
    boost多线程入门介绍
    boost中bind的使用
    c++11新标准for循环和lambda表达式
    使用gcc命令编译多个文件
    编辑gif
  • 原文地址:https://www.cnblogs.com/yc3110/p/10443327.html
Copyright © 2011-2022 走看看