zoukankan      html  css  js  c++  java
  • python类中特殊方法

    1、__doc__

    打印当前类的描述信息,也就是注释部分。

    class test(object):
        """
        this is a msg
        """
        pass
    print(test.__doc__)
    
    #输出 this is a msg

    2、__class__

    输出当前实例的类名

    class test():
        def foo(self):
            print(123)
    obj = test()
    print(obj.__class__)
    #输出<class '__main__.test'>
    

    3、__str__

    如果类中有str方法的话直接打印实例,会输出str方法中定义的返回内容,而非一个内存地址

    class test():
        def __str__(self):
            return('this is a msg')
    obj = test()
    print(obj)
    #输出this is a msg
    

    4、__dict__

    打印类中的属性。

    class test():
        def A(self):
            a = 1
        def B(self):
            pass
        def __str__(self):
            return('this is a msg')
    obj = test()
    print(test.__dict__)
    #输出{'__module__': '__main__', 'A': <function test.A at 0x00FBA540>, 'B': <function test.B at 0x00FBA588>, '__str__': <function test.__str__ at 0x00FBA5D0>, '__dict__': <attribute '__dict__' of 'test' objects>, '__weakref__': <attribute '__weakref__' of 'test' objects>, '__doc__': None}
    

    5、__init__

    构造方法,创建实例时候会自动执行,面向对象中非常常用,一般用来封装各种参数

    class test():
        def __init__(self,name,age):
            print(name,age)
    obj = test('django','18')
    #输出django 18
    

    6、__del__

    与 init() 方法对应的是 __del__() 方法,__init__() 方法用于初始化 Python对象,而 __del__() 则用于销毁 Python 对象,即在任何 Python 对象将要被系统回收之时,系统都会自动调用该对象的 __del__() 方法。

    class test():
        def __init__(self,name,age):
            print(name,age)
        def __del__(self):
            print("回收")
    obj = test('django','18')
    

    7、__call__

    加括号执行

    class test():
        def __call__(self, *args, **kwargs):
            print('call')
        def a(self):
            print('a')
    obj = test()
    obj()
    obj.a()
    #输出call,a


    8、__new__

    new方法和init方法的区别就是,new方法是正在创建实例时候执行,而init方法是创建实例后才执行。

    class PositiveInteger(int):
        def __new__(cls, value):
            return super(PositiveInteger, cls).__new__(cls, abs(value))
    i = PositiveInteger(-3)
    print(i)

    __new__方法单机实例

    class Singleton(object):
        def __new__(cls):
            # 关键在于这,每一次实例化的时候,我们都只会返回这同一个instance对象
            if not hasattr(cls, 'instance'):
                cls.instance = super(Singleton, cls).__new__(cls)
            return cls.instance
    obj1 = Singleton()
    obj2 = Singleton()
    

     自定义构建函数

    class asd(object):
        def __new__(cls, *args, **kwargs):
            r = super(asd,cls).__new__(cls)
            r.initialize(*args)
            return r
    
    class bnm(asd):
    
        def initialize(self):
            print('bnm_initialize is running')
    
    class foo(asd):
    
        def initialize(self,name):
            self.name = name
            print('foo_initialize is running, my name is %s' %(self.name))
    
    
    r = bnm()
    r1 = foo('test')
    

    9、__getitem__   __setitem__   __delitem__

    用于索引操作,如字典。以上分别表示获取、设置、删除数据

    #coding=utf-8
    class Foo(object):
        def __getitem__(self, key):
            print('__getitem__', key)
    
        def __setitem__(self, key, value):
            print('__setitem__', key, value)
    
        def __delitem__(self, key):
            print('__delitem__', key)
    obj = Foo()
    result = obj['k1']  # 自动触发执行 __getitem__
    obj['k2'] = 'alex'  # 自动触发执行 __setitem__
    del obj['k1']     # 自动触发执行 __delitem__
    #输出
    #__getitem__ k1
    #__setitem__ k2 alex
    #__delitem__ k1
    

      

    Welcome to visit
  • 相关阅读:
    项目管理系列(其他):国际工程承包项目风险识别与分析
    公司注册之简化版
    公司注册之百度百科
    有效投标不足三家不应是重新招标的必要条件
    CPU频率
    集成电路
    晶体管
    Oracle问题之ORA-01609、ORA-00362
    Oracle问题之ORA-12560TNS:协议适配器错误
    Oracle问题之字符集问题,登陆sqlplus出现问号
  • 原文地址:https://www.cnblogs.com/Nolover/p/10997444.html
Copyright © 2011-2022 走看看