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
  • 相关阅读:
    解决 react-native 嵌套路由 warning
    在 function component 中设置 navigationOptions
    《客户端存储技术》阅读笔记
    表单实现原理(Vue ElementUI)
    MVVM 响应式原理(Vue)
    react 实现 loading 动效圈,支持配置转一圈的 duration
    CSS 数字设置等宽
    JSONP(Json with padding)
    javascript this对象
    css盒子模型
  • 原文地址:https://www.cnblogs.com/yc3110/p/10443327.html
Copyright © 2011-2022 走看看