""" """
__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__定义的属性仅对当前类实例起作用,对继承的子类是不起作用
转载于:https://www.cnblogs.com/shaozhiqi/p/11550464.html
相关资源:Python中的__slots__示例详解