第四发

python可以给class实例绑定属性和方法,例:

s = Student()
s.age =10#动态属性

def sayHello(self):
    print "hello"

from types import MethodType
s.sayHello = MethodType(sayHello,s,Student)#动态方法

s.sayHello()

上面是给class实例添加动态方法,如果想给class添加动态方法,需要:

Student.sayHello = MethodType(sayHello,None,Student)

如果不想动态给class动态添加属性或方法,需要用到__slots__来限制,例:

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

s = Student()
s.age = 10#报错,如果Student继承的基类中没有object的影子,__slots__不发挥作用

__slots__定义的属性只对当前类发挥作用,如果想让子类也发挥作用,需要在子类中也定义__slots__,这样子类和父类的slots都会在子类中发挥作用

posted @ 2015-11-04 16:31  helloWorld我来了  阅读(148)  评论(0编辑  收藏  举报