面向对象内置方法之--__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}

  

原文地址:https://www.cnblogs.com/qianzhengkai/p/10791094.html