设为首页 加入收藏

TOP

Python使用__slots__限制实例属性
2019-03-05 10:08:42 】 浏览:56
Tags:Python 使用 __slots__ 限制 实例 属性
#定义一个类Student
class Student(object):
    __slots__ = ('name','age') #用元组(tuple)的形式绑定属性名称

s = Student()
s.name = 'xh'
print s.name  #xh

#s.score = 88  #因为 __slots__中没有score属性,所以报错
#print s.score  #AttributeError: 'Student' object has no attribute 'score'

#定义一个类MidStudent继承于Student
class MidStudent(Student):
    pass
m = MidStudent()
m.name = 'xm'
print m.name  #xm

#虽然父类对属性进行了限制,但子类不受影响
m.score = 88
print m.score  #88

 

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇分别给Python类和实例增加属性和.. 下一篇Python3 数值类型与运算符

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目