Python __SLOTS__属性 Python中的__SLOTS__属性使用示例

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Python __SLOTS__属性 Python中的__SLOTS__属性使用示例

  2021-03-21 我要评论
想了解Python中的__SLOTS__属性使用示例的相关内容吗,在本文为您仔细讲解Python __SLOTS__属性的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Python,__SLOTS__,属性,下面大家一起来学习吧。

看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 


Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们