__slots__,限制绑定属性,对子类不起作用
class Student(object):
__slots__ = ('score','name') #可限制绑定属性,用tuple定义属性名称
def set_name(self, name):
self.name = name
from types import MethodType
#MethodType可将方法绑定在实例上,但是对另一实例是不起作用的
s1 = Student()
s1.set_name = MethodType(set_name,s1)
s2 = Student()
s1.set_name('tom')
s2.set_name('tony')
print (s1.name)# tom
print (s2.name)#报错
class Student(object):
__slots__ = ('score','name') #可限制绑定属性
def set_name(self, name):
self.name = name
Student.set_name = set_name #将方法绑定到类上,对任何实例都起作用
s1 = Student()
s2 = Student()
s1.set_name('tom')
s2.set_name('tony')
print (s1.name)# tom
print (s2.name)#tony
class Student(object):
__slots__ = ('score') #可限制绑定属性
def set_name(self, name):
self.name = name
Student.set_name = set_name #将方法绑定到类上,对任何实例都起作用
s1 = Student()
s2 = Student()
s1.set_name('tom')
s2.set_name('tony')
print (s1.name)#
print (s2.name)#报错,由于类中限制了属性score,name属性无法被绑定