zoukankan      html  css  js  c++  java
  • 面向对象内置方法之--__str__、__call__、__del__

    1. __str__: 在对象被打印的时候触发,可以用来定义对象被打印的输出格式
    2. __del__:在对象被删除的时候触发,可以 用来回收对象以外的其他相关资源,比如系统资源等。
    3. __call__:在对象呗调用的时候触发。
    # -*- coding: utf-8 -*-
    """
    __str__: 在对象被打印是自动触发,可以用来定义对象被打印时的输出信息
    
    
    """
    
    
    class People:
        def __init__(self, name, age):
            self.name = name
            self.age = age
    
    
    obj1 = People('egon', 18)
    print(obj1)  # <__main__.People object at 0x00000000028B7438>
    obj2 = list([1, 2, 3])
    print(obj2)  # [1, 2, 3]  内置的数据类型,已经定义好打印格式
    
    
    class People:
        def __init__(self, name, age):
            self.name = name
            self.age = age
        
        def __str__(self):
            return '<name:%s | age:%s>' % (self.name, self.age)
    
    
    obj1 = People('egon', 18)
    print(obj1)  # <name:egon | age:18> # 通过 __str__自定义数据类型
    
    """
    __del__: 在对象被删除时自动触发,可以用来回收对象意外其他相关资源,比如系统资源
    """
    
    
    class Foo:
        pass
    
    
    obj = Foo()
    del obj  # 主动删除
    
    
    class Foo:
        def __init__(self, x, filepath, encoding='utf-8'):
            self.x = x
            self.f = open(filepath, 'rt', encoding='utf-8')
        
        def __del__(self):
            print('run.....回收对象关联的资源')
            # 回收对象关联的资源
            self.f.close()
    
    
    obj = Foo(1, 'a.txt')
    print('============')
    # ============
    # run.....回收对象关联的资源
    
    
    """
    __call__:在对象被调用的时候触发
    """
    
    
    class Foo:
        def __init__(self, x, y):
            self.x = x
            self.y = y
    
    
    obj3 = Foo(1, 2)
    
    
    # obj()  # TypeError: 'Foo' object is not callable
    print('+++++++++++++++++++++++++++++++++')
    class Foo1:
        def __init__(self, x, y):
            self.x = x
            self.y = y
        
        def __call__(self, *args, **kwargs):
            print(self, args, kwargs)
    
    
    obj2 = Foo1(1, 2)
    obj2(1,2,a=3,b=4)  # <__main__.Foo1 object at 0x0000000002304278> (1, 2) {'a': 3, 'b': 4}
    

      

  • 相关阅读:
    去掉影响美观的横滚动条
    Visio绘制事件分解图
    Visio绘制系统图
    asp.net与js中字符串的HTML编码与解码
    《ERP从内部集成起步》读书笔记——第一章 Garthner公司是如何提出ERP的 1.1尊重历史
    Asp.net页面传参数给Silverlight
    Gridview中格式化数据的方法
    让silverlight不在最顶层,可以在悬浮层之下
    DateTime类型中 DayOfWeek时的英文如何转换成中文(转)
    Asp.net页面中通过Js控制Silverlight显示值
  • 原文地址:https://www.cnblogs.com/qianzhengkai/p/10791094.html
Copyright © 2011-2022 走看看