Python中的__SLOTS__属性使用示例

yipeiwu_com6年前Python基础

看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 


相关文章

Python对数据进行插值和下采样的方法

使用Python进行插值非常方便,可以直接使用scipy中的interpolate import numpy as np x1 = np.linspace(1, 4096, 1024...

python 字典操作提取key,value的方法

python 字典操作提取key,value的方法

python 字典操作提取key,value dictionaryName[key] = value 1.为字典增加一项 2.访问字典中的值 3、删除字典中的一项...

使用pygame写一个古诗词填空通关游戏

使用pygame写一个古诗词填空通关游戏

之前写的诗词填空的游戏支持python2,现在对程序进行了修改,兼容支持python2和python3,附下效果图。 下面是两个主程序 idiom_lib.py代码: # -*-...

解决win64 Python下安装PIL出错问题(图解)

解决win64 Python下安装PIL出错问题(图解)

1、软件版本 首先我先安装了 python 2.7 pip是  8.1.2 2、当我要安装PIL时,我在cmd下面输入:pip install PIL 错误提示是: Coul...

Selenium chrome配置代理Python版的方法

环境: windows 7 + Python 3.5.2 + Selenium 3.4.2 + Chrome Driver 2.29 + Chrome 58.0.3029.110 (64...