zoukankan      html  css  js  c++  java
  • 面向对象:其他双下方法

    __str__和__repr__

    print(obj)  或  "s%" % obj  或  str(obj)  的时候,实际上是调用了__str__方法,返回的是一个字符串

    class Foo(object):
        def __str__(self):
            return "__str__"
    
        def __repr__(self):
            return "__repr__"
    
    obj = Foo()
    
    print(obj)         # __str__
    print("%s" % obj)  # __str__
    print(str(obj))    # __str__
    View Code

    如果没有__str__方法,会先找本类中的__repr__方法,再没有就再找父类中的__str__

    class Foo(object):
    
        def __str__(self):
            return "Foo.__str__"
    
    class Bar(Foo):
        pass
    
    obj = Bar()
    
    print(obj)         # Foo.__str__
    print("%s" % obj)  # Foo.__str__
    print(str(obj))    # Foo.__str__
    View Code

    repr()只会找__repr__,如果本类没有就找父类的

    class Foo(object):
        def __repr__(self):
            return "Foo.__repr__"
    
    class Bar(Foo):
        pass
    
    obj = Bar()
    print(repr(obj))  # Foo.__repr__
    View Code

    __del__

    析构方法:当对象在内存中被释放时,自动触发执行(在删除一个对象之前进行一些收尾工作)。

    注:此方法一般无须定义,因为Python是一门高级语言,程序员在使用时无需关心内存的分配和释放,因为此工作都是交给Python解释器来执行。所以,析构函数的调用是由解释器在进行垃圾回收时自动触发执行的。

    class Foo(object):
        def __del__(self):
            print("执行__del__")
    
    obj=Foo()
    del obj
    print("*"*10)
    """
    执行__del__
    **********
    """
    View Code

    __call__

    对象后面加括号,触发执行。
    注:构造方法 __new__ 的执行是由创建对象触发的,即:对象 = 类名();而对于 __call__ 方法的执行是由对象后加括号触发的,即:对象() 或者 类()()

    class Foo(object):
        def __init__(self):
            print("执行__init__")
    
        def __call__(self, *args, **kwargs):
            print("执行__call__")
    
    obj = Foo()  # 执行__init__
    obj()        # 执行__call__
    View Code

    __len__、__dict__

    class Foo(object):
        def __init__(self):
            self.a = 1
            self.b = 2
    
        def __len__(self):
            return len(self.__dict__)
    
    
    obj = Foo()
    print(obj.__dict__)  # {'b': 2, 'a': 1}
    print(len(obj))      # 2
    View Code

    __hash__

    class Foo(object):
        def __init__(self, name, age):
            self.name = name
            self.age = age
    
        def __hash__(self):
            return hash(self.name + str(self.age))
    
    
    a = Foo("aa", 10)
    b = Foo("bb", 20)
    
    print(hash(a))
    print(hash(b))
    View Code

    __eq__

    class Foo(object):
        def __init__(self, name):
            self.name = name
    
        def __eq__(self, other):
            if self.__dict__ == other.__dict__:
                return True
            else:
                return False
    
    obj1 = Foo("xx")
    obj2 = Foo("xx")
    print(obj1 == obj2)  # True
    View Code

    __new__

    构造方法:用来创建一个对象

    class Foo(object):
        def __init__(self):
            print("init function")
    
        def __new__(cls, *args, **kwargs):  # __new__借助object创建self对象
            print("new function")
            return object.__new__(Foo)
    
    obj = Foo()
    # 打印结果
    """
    new function
    init function
    """
    View Code

    单例模式:

    • 一个类始终只有一个实例;
    • 当第一次实例化这个类的时候,就创建一个实例化的对象;
    • 当之后再实例化的时候,就用之前创建的对象。
    class Singleton(object):
        __instance = None
    
        def __init__(self, name, age):
            self.name = name
            self.age = age
    
        def __new__(cls, *args, **kwargs):
            if cls.__instance is None:
                cls.__instance = object.__new__(cls)
            return cls.__instance
    
    
    obj1 = Singleton("盲僧", 10)
    obj2 = Singleton("德玛", 20)
    
    print(obj1)  # <__main__.Foo object at 0x0000000000B7B908>
    print(obj2)  # <__main__.Foo object at 0x0000000000B7B908>
    
    print(obj1.name)  # 德玛
    print(obj2.name)  # 德玛
    View Code
    class Foo(object):
        __instance = None
    
        @staticmethod
        def singleton():
            if Foo.__instance:
                return Foo.__instance
            else:
                Foo.__instance = Foo()
                return Foo.__instance
    
    
    obj1 = Foo.singleton()
    obj2 = Foo.singleton()
    
    print(obj1)  # <__main__.Foo object at 0x000000000109B5F8>
    print(obj2)  # <__main__.Foo object at 0x000000000109B5F8>
    View Code
  • 相关阅读:
    java 日期格式 毫秒 表示方法
    Java的框架是什么意思
    圣思源Java视频36节练习源码分享(自己的190+行代码对比老师的39行代码)
    预装win8的笔记本如何重装win7
    Word 2013 无法撤销操作的错误
    面试经验分享(跳槽季~~~❀)
    一些可能有点用处的C#开发经验
    电子设计解决方案透视
    突破限速
    当区块链遇上Rust
  • 原文地址:https://www.cnblogs.com/believepd/p/9670495.html
Copyright © 2011-2022 走看看