• linkedu视频
  • 平面设计
  • 电脑入门
  • 操作系统
  • 办公应用
  • 电脑硬件
  • 动画设计
  • 3D设计
  • 网页设计
  • CAD设计
  • 影音处理
  • 数据库
  • 程序设计
  • 认证考试
  • 信息管理
  • 信息安全
菜单
linkedu.com
  • 网页制作
  • 数据库
  • 程序设计
  • 操作系统
  • CMS教程
  • 游戏攻略
  • 脚本语言
  • 平面设计
  • 软件教程
  • 网络安全
  • 电脑知识
  • 服务器
  • 视频教程
  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell
您的位置:首页 > 脚本语言 >python > Python中的__SLOTS__属性使用示例

Python中的__SLOTS__属性使用示例

作者:junjie 字体:[增加 减小] 来源:互联网

junjie 通过本文主要向大家介绍了python slots,slots,slots是什么意思,extra equip slots,slots游戏等相关知识,希望对您有所帮助,也希望大家支持linkedu.com www.linkedu.com

看python社区大妈组织的内容里边有一篇讲python内存优化的,用到了__slots__。然后查了一下,总结一下。感觉非常有用

python类在进行实例化的时候,会有一个__dict__属性,里边有可用的实例属性名和值。声明__slots__后,实例就只会含有__slots__里有的属性名。

# coding: utf-8
 
 
class A(object):
  x = 1
 
  def __init__(self):
    self.y = 2
 
a = A()
print a.__dict__
print(a.x, a.y)
a.x = 10
a.y = 10
print(a.x, a.y)
 
 
class B(object):
  __slots__ = ('x', 'y')
  x = 1
  z = 2
 
  def __init__(self):
    self.y = 3
    # self.m = 5 # 这个是不成功的
 
 
b = B()
# print(b.__dict__)
print(b.x, b.z, b.y)
# b.x = 10
# b.z = 10
b.y = 10
print(b.y)
 
 
class C(object):
  __slots__ = ('x', 'z')
  x = 1
 
  def __setattr__(self, name, val):
    if name in C.__slots__:
      object.__setattr__(self, name, val)
 
  def __getattr__(self, name):
    return "Value of %s" % name
 
 
c = C()
print(c.__dict__)
print(c.x)
print(c.y)
# c.x = 10
c.z = 10
c.y = 10
print(c.z, c.y)
c.z = 100
print(c.z)

{'y': 2}
(1, 2)
(10, 10)
(1, 2, 3)
10
Value of __dict__
1
Value of y
(10, 'Value of y')
100 
</div>


</div>

您可能想查找下面的文章:

  • python中__slots__用法实例
  • 在Python中使用__slots__方法的详细教程
  • 用Python中的__slots__缓存资源以节省内存开销的方法
  • python中的__slots__使用示例
  • Python中的__SLOTS__属性使用示例

相关文章

  • Python实现控制台进度条功能
  • 布同 统计英文单词的个数的python代码
  • python插入排序算法实例分析
  • Python中的默认参数详解
  • python logging类库使用例子
  • python实现从ftp服务器下载文件的方法
  • 用Python编写一个简单的Lisp解释器的教程
  • Python用Bottle轻量级框架进行Web开发
  • Python的Socket编程过程中实现UDP端口复用的实例分享
  • Python中的anydbm模版和shelve模版使用指南

文章分类

  • vbs
  • DOS/BAT
  • hta/htc
  • python
  • perl
  • VBA
  • ColdFusion
  • ruby
  • PowerShell
  • Lua
  • Golang
  • linux shell

最近更新的内容

    • 用Python实现web端用户登录和注册功能的教程
    • Python中数字以及算数运算符的相关使用
    • Python中取整的几种方法小结
    • 一个基于flask的web应用诞生 使用模板引擎和表单插件(2)
    • 跟老齐学Python之集合(set)
    • python解决网站的反爬虫策略总结
    • python模块简介之有序字典(OrderedDict)
    • Python装饰器的函数式编程详解
    • 浅要分析Python程序与C程序的结合使用
    • Python and、or以及and-or语法总结

关于我们 - 联系我们 - 免责声明 - 网站地图

©2020-2025 All Rights Reserved. linkedu.com 版权所有