设为首页 加入收藏

TOP

Python类中的魔法方法之 __slots__
2019-09-03 03:44:34 】 浏览:98
Tags:Python 魔法 方法 __slots__

在类中每次实例化一个对象都会生产一个字典来保存一个对象的所有的实例属性,这样非常的有用处,可以使我们任意的去设置新的属性。


可通过__slots__方法告诉python不要使用字典,而且只给一个固定集合的属性分配空间


class Foo(object):
    __slots__ = ("x","y","z")


    def __init__(self,x,y):
        self.x = x
        self.y = y
        self.z = None


    def tell_info(self,name):
      return  getattr(self,name)


c = Foo(10,20)
# 设置和获取__slots__中设置的可访问实例属性
print(c.tell_info("x"))      # 结果:10


c.z=50
print(c.tell_info("z"))  # 结果:50


# 设置一个不在__slots__中存在的属性,会报错
c.e = 70    # AttributeError: 'Foo' object has no attribute 'e'


# 访问对象.__dict__ 也会直接报错
print(c.__dict__) # AttributeError: 'Foo' object has no attribute '__dict__'


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇详述 Python 全局变量 下一篇Spring中的循环依赖解决详解

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目