1. 为instance动态增加属性和方法
class Student(object):
pass
s1 = Student()
#给s1新增属性
s1.name = 'haozhang'
print(s1.name,'\n')
#给s1新增方法
def SetAge(self,age): #此处同时还新增了实例属性属性age
self.age = age
from types import MethodType
s1.SetAge = MethodType(SetAge, s1)
s1.SetAge(120) #活到120,哈哈哈
print(s1.age, '\n')
2. 给class即Student绑定属性,这样对所有Student的instance都生效
Student.name = 'I am Student' #{类属性}
s2 = Student()
print(s2.name,'\n')
#给class新增 {类方法}
def SetScore(self,score):
self.score = score #这里等价于也新增了实例属性score
Student.SetScore = SetScore #直接把刚外部定义的方法传给Student
s3 = Student()
s3.SetScore(101)
s2.SetScore(102)
s1.SetScore(103)
print(s3.score, '\n')
print(s2.score, '\n')
print(s1.score, '\n')
3. 限制当前类{但是无法管辖其子类}的所有instance的“新增属性”
class Animal(object):
__slots__ = ('name','age') #用tuple来限定Animal的所有instance的属性,但是无法
#无法限制Animal的子类的instance的属性
a1 = Animal()
a2 = Animal()
a3 = Animal()
a1.name = 'a1'
a2.age = 123
#a3.gender = 'female' #会报错:没有这样的attribution
#但是Animal的子类却不受限制
class Dog(Animal):
pass
d = Dog()
d.gender = 'male' #这是Animal限制之外的属性
print(d.gender,'\n') #完全OK