详解:python属性函数和内存管理

ernestwang 834 0

属性函数

说明:将成员方法当做属性一样访问 个人理解:获取类的对象的方法,然后对获取的方法进行重写,装饰。变成自己的属性。 class User: def __init__(self, username, password): self.username = username self.password = password   # 获取器:获取password属性时自动触发  @property def password(self): print('你想干啥?') return '偷看密码,没门'   # 设置器:设置password属性时自动触发 @password.setter def password(self, password): print('设置密码', password) self.__dict__['password'] = 'xxx' + password + 'yyy'     user = User('xiaoming', '123456') print(user.password)   获取器:获取password属性时自动触发 设置器:设置password属性时自动触发  

内存管理

  From sys import getrefcount   引入getrefcount模块。统计对象被引用的次数。当对象的被引用的次数减为0的时候,调用__del__方法。释放相关的资源。 代码实现: a = 10 b = 10   print(id(a)) print(id(b))   from sys import getrefcount   # 不可变变量的引用计数没有意义 print(getrefcount(a))   lt = [1, 2, 3]   lt2 = lt   # 函数本身会增加1次引用计数 print(getrefcount(lt)) del lt2 print(getrefcount(lt))   class Person: def __del__(self): print('对象即将释放')   p = Person() print(getrefcount(p))   del p print('OVER')   引用传递 # 不可变变量传递的是值 #可变变量传递的引用 #默认值是可变变量。永远都是同一个  

标签: python函数 内存管理 python

发布评论 0条评论)

还木有评论哦,快来抢沙发吧~

复制成功
微信号: irenyuwang
关注微信公众号,站长免费提供流量增长方案。
我知道了