首页 > 编程语言 > 详细

python3(二十六)slots

时间:2019-09-19 16:15:57      阅读:83      评论:0      收藏:0      [点我收藏+]
"""  """
__author__ = shaozhiqi


# python是动态语言,所以定义类后,我们可以动态的给类绑定属性和方法,上一节都都与接触
class Student(object):
    pass


s = Student()
s.name = shaozhiqi
print(s.name)  # shaozhiqi


# 定义一个方法,绑定到s对象上,不会影响别的实例
def set_age(self, age):
    self.age = age


from types import MethodType

s.set_age = MethodType(set_age, s)
s.set_age(25)
print(s.age)  # 25

# 给类绑定方法
s1 = Student()
# s1.set_age(26)  # error
# print(s1.age) # error
Student.set_age = set_age
s2 = Student()
s2.set_age(30)
print(s2.age)  # 30


# -----------slots---------------------------------------
class Student(object):
    __slots__ = (name, age)  # 用tuple定义允许绑定的属性名称


ss = Student()
ss.name = shaozhiqi
# ss.score = ‘99‘  # error   不允许添加score属性

# __slots__要注意,__slots__定义的属性仅对当前类实例起作用,对继承的子类是不起作用

 

python3(二十六)slots

原文:https://www.cnblogs.com/shaozhiqi/p/11550464.html

(1)
(1)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!