zoukankan      html  css  js  c++  java
  • 特殊方法/特殊属性

    知识点一:初始化/析构

      “初始化”特殊方法

    在python中有很多以双下划线开头且也双下划线结尾的固定方法。

    他们会在特定的时机被触发执行。

    __init__就是其中之一,他会在实例化之后自动被调用,已完成实例的初始化。

       __init__的参数传递过程

    析构:

    在对象被销毁的时候,获得执行特定任务的机会

    提示开发者,对象被销毁了,方便调试。进行一些必要的清理操作。

    基于变量计数的对象销毁机制

    当没有一个变量指向某个对象的时候,Python会自动销毁这个对象,以便回收内存空间。

    del 关键字,可以删除一个变量的指向。

    释放资源后,自动执行__del__内的定义:

    class Account:
        def __init__(self,name,number,balance):
            self.name=name
            self.number=number
            self.balance=balance
        def __del__(self):
            print(self.name,'被销毁了!')
    
        def deposit(self,mount):
            if mount <=0:
                print ("不能存负数金额")
            else:
                self.balance+=mount
    
        def withdraw(self,mount):
            if mount >self.balance:
                print("余额不足!")
            else:
                self.balance-=mount
        def desc(self):
            return '{name} :{balance}'.format(name=self.name,
                                              balance=self.balance)
    p=Account('Tuple','1234123',8888)
    p.deposit(2000)
    p.withdraw(1500)
    print(p.desc())
     

    Tuple :9388
    Tuple 被销毁了!

    看一个__del__实例

    如果没有a.close(),即使删除了a实例,实例对象也不会被销毁,不能够调用到__del__方法的定义,Account中也有值。入下:

    class Account:
        all_accounts= {}
    
        def __init__(self,name,number,balance):
            self.name=name
            self.number=number
            self.balance=balance
            self.all_accounts[number]=self
    
        def deposit(self,mount):
            if mount <=0:
                print ("不能存负数金额")
            else:
                self.balance+=mount
    
        def withdraw(self,mount):
            if mount >self.balance:
                print("余额不足!")
            else:
                self.balance-=mount
        def close(self):
            self.all_accounts.pop(self.number)
    
        def __str__(self):
            return '{name} :{balance}'.format(name=self.name,
                                              balance=self.balance)
        def __repr__(self):
            return 'Account({name} :{number}:{balance})'.format(name=self.name,
                                            number=self.number,
                                              balance=self.balance)
        def __del__(self):
            print(self.name,'被销毁了!')
    p=Account('Tuple','1234123',8888)
    p.deposit(2000)
    p.withdraw(1500)
    print(p)
    #p.close()
    del p
    print(Account.all_accounts)

    Tuple :9388
    {'1234123': Account(Tuple :1234123:9388)}

    知识点二:字符串表示

    功能点:在不需要专门调用一个描述方法的前提下就展示实例信息。

    对使用者使用友好的 __str__

    对开发者调试有好的 __repr__

    class Account:
    
        def __init__(self,name,number,balance):
            self.name=name
            self.number=number
            self.balance=balance
    
        def __str__(self):
    #向使用者提供尽可能简洁且有用的信息
    return '{name} :{balance}'.format(name=self.name, balance=self.balance) def __repr__(self):
    #向开发者提供接近创建时的信息
    return 'Account({name} :{number}:{balance})'.format(name=self.name, number=self.number, balance=self.balance) def __del__(self): print(self.name,'被销毁了!') p=Account('Tuple','1234123',8888) print(p) #打印出__str__的返回值 print('-----------------------') print(str(p)) print(repr(p)) # 打印出__repr__的返回值 print('-----------------------') 调试结果: Tuple :8888 ----------------------- Tuple :8888 Account(Tuple :1234123:8888) ----------------------- Tuple 被销毁了!

     在交互模式下输出的交互信息与直接print的信息有些不同,背后的原理:

    __str__与__repr__该如何抉择

    str:尽可能的提供简洁且有用的信息,让用户尽可能吸收到必要的信息

    repr:尽可能向开发者提供创建该对象时的必要信息,让开发者可以直接通过复制粘贴开重建对象。

    知识点三:属性访问

    “属性操作”内置函数

    getattr(object,'name',[,default] --->object.name

    hasattr(object,'name')

    setattr(object,'name',value)  ---->object.name=value

    delattr(object,'name')  --->del object.name

    运行时决定操作的属性

    除此之外,hasattr还可以避免,因为没有属性而导致的报错。

    知识点四:特殊属性

  • 相关阅读:
    怎样使用Chrome模拟手机浏览器測试移动端网站
    [Erlang危机](5.1.3)进程
    Oracle ErrorStack 使用和阅读具体解释
    动态规划之整齐打印
    struts2+Oracle实现管理员查看用户提交的意见功能
    hdu 4956 Poor Hanamichi BestCoder Round #5(数学题)
    2014牡丹江——Known Notation
    诗云:静观天下
    QQ欢乐斗地主心得体会 (三):高倍场攻略
    QQ欢乐斗地主心得体会 (三):高倍场攻略
  • 原文地址:https://www.cnblogs.com/taoge188/p/8504969.html
Copyright © 2011-2022 走看看