python 使用__slots__

来源:互联网 发布:warframe端口脱机 编辑:程序博客网 时间:2024/06/06 07:33
使用__slots__:正常情况下,当我们定义了一个class,创建了夜歌class的实例后,我们可以给该梳理绑定任何属性和方法,给实例绑定一个属性:class Student(object):   passs=Student()s.name='aaa'print s.name给class 绑定方法:使用__slots__class Student(object):   passs=Student()s.name='aaaa's.score='bbbb's.age='ccc'print s.nameprint s.scoreprint s.ageC:\Python27\python.exe C:/Users/TLCB/PycharmProjects/untitled/mycompany/cookbook/a21.pyaaaabbbbccc为了达到限制的目的,Python允许在定义class的时候,定义一个特殊的__slots__变量,来限制该class能添加的属性:# !/usr/bin/env python# -*- coding: utf-8 -*-class Student(object):    __slots__ = ('name', 'age')  # 用tuple定义允许绑定的属性名称s=Student()s.name='aaaa's.score='bbbb's.age='ccc'print s.nameprint s.scoreprint s.ageC:\Python27\python.exe C:/Users/TLCB/PycharmProjects/untitled/mycompany/cookbook/a21.pyTraceback (most recent call last):  File "C:/Users/TLCB/PycharmProjects/untitled/mycompany/cookbook/a21.py", line 7, in <module>    s.score='bbbb'AttributeError: 'Student' object has no attribute 'score'

原创粉丝点击