• 类的魔法方法


    1:_doc_

    这是类的文档注释

    class T:
        '''
        这是类T的注释文档
        '''
        
    print(T.__doc__) # 这是类T的注释文档
    obj = T()
    print(obj.__doc__) # 这是类T的注释文档
    

    2.__module__和__class__的用法

    __module__ 表示当前操作的对象在哪个模块

    __class__ 表示当前操作的对象的类是什么

    from multiprocessing import Process
    
    
    def test():
        pass
    
    if __name__ == "__main__":
        p1 = Process(target=test)
        print(p1.__module__)  #  multiprocessing.context 类所在的模块
        print(p1.__class__)  # <class 'multiprocessing.context.Process'> 类名
    
    

    3:__init__

    构造方法,在调用类时自动触发

    class Teacher():
        def __init__(self,name,age):
            self.name = name
            self.age = age
        def run(self):
            pass
    print(Teacher.name)  # 报错没有这个属性 
    
    ojb = Teacher('beautify',18)
    print(ojb.name)  # beautify
    print(ojb.age)  # 18
      
    print(Teacher('beautify',18).name) # beautify
    print(Teacher('beautify',18).age)  # 18
    
    

    4.__del__

    当对象运行结束时,自动触发这里的方法,一般是用于垃圾回收

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

    import time
    class Bar():
        def __init__(self,name,age):
            self.name = name
            self.age = age
        def __del__(self):
            print("运行结束")
    		
            
    ojb = Bar('alen',88)
    print(ojb.name)  # alen
    print(ojb.age)  # 88
    time.sleep(1)
    
    def test():
        pass
    
    test()
    # 当次页面执行结束时,__del__自动触发
    

    5.__call__

    对象加括号可以执行。

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

    class Bar():
        def _init__(self):
            self.name = name
            self.age = age
            
       	
        def __call__(self,*args,**kwargs):
            print('这就是call方法')
            return Bar(*args,**kwargs)
    
        
    obj = Bar('alen', 88)
    test = obj('alex', 18)  # 对象调用方法,产生对象
    print(test.name)
    print(test.age)
    
    

    6.__dict__

    类或对象中的所以成员

    类的普通字段属于对象;类中的静态字段和方法等属于类·

    class Peopel(object):
        province = 'cn'
        def __init__(self,name,count):
            self.name = name
            self.count = count
            
         def test(sefl,*args,**kwargs):
            print("这是一个测试函数")
            
    print(Peopel.__dict__)  # 查看类的属性(静态,字段,方法)
    # {'__module__': '__main__', 'province': 'cn', '__init__': <function People.__init__ at 0x000001953227B280>, 'test': <function People.test at 0x000001953227B1F0>, '__dict__': <attribute '__dict__' of 'People' objects>, '__weakref__': <attribute '__weakref__' of 'People' objects>, '__doc__': None}
    
    obj1 = People('alex',8)
    print(obj1.__dict__)  # {'name': 'alex', 'count': 18}
    obj2 = People('alex',28)  # {'name': 'alex', 'count': 28}
    

    7:__str__

    如果一个类中定义了__str__方法,那么在打印 对象 时,默认输出该方法的返回值。

    class Foo:
        
        def __init__(self,name,age):
            self.name = name
            self.age = age
            
        def __str__(self):
            return f'<{self.name}>'
        
    alex = Foo('alex',18)
    print(alex)  # <alex> 
    

    8:__repr__

    这个方法和__str__方法很相似,如果class内部出现了__str__方法优先调用__str__方法

    示例一:

    
    class Bar():
        def __init__(self, name, age):
            self.name = name
            self.age = age
    
        def __repr__(self):
            return f'<{self.name} is age {self.age}>'
    
    
    alex = Bar('alen', 18)
    print(alex)  # <alen is age 18>
    
    class Bar():
        def __init__(self,name,age):
            self.name = name 
            self.age = age
        def __str__(self):
            return '{} is age {}'.format(self.name,self.age)
        
        def __repr__(self):
            return f'<{self.name} age is  {self.age}>'
        
    alex = Bar('alen',18)
    print(alex)  # alen age is 18
    
  • 相关阅读:
    Sqlite Administrator
    在资源管理器/我的电脑详细信息视图里按下Ctrl+(小键盘+)
    Asp.net 2.0 Membership Provider for db4o 6.1
    测试使用Zoundry发布blog
    我的WCF之旅(8):WCF中的Session和Instancing Management
    我的WCF之旅(7):面向服务架构(SOA)和面向对象编程(OOP)的结合——如何实现Service Contract的继承
    我的WCF之旅(5):面向服务架构(SOA)和面向对象编程(OOP)的结合——如何实现Service Contract的重载(Overloading)
    我的WCF之旅(4):WCF中的序列化[上篇]
    我的WCF之旅(6):在Winform Application中调用Duplex Service出现TimeoutException的原因和解决方案
    我的WCF之旅(4):WCF中的序列化[下篇]
  • 原文地址:https://www.cnblogs.com/wait59/p/13634969.html
Copyright © 2020-2023  润新知