#给实例绑定属性stu.age=30print"age is %d"%stu.age#给shi例绑定方法defset_age(self,age):self.age=agefromtypesimportMethodTypestu.set_age=MethodType(set_age,stu,Student)stu.set_age(40)print"age is %d"%stu.age#给一个实例绑定的方法,对另一个实例是不起作用的#stu2=Student("hello",80)#stu2.set_age(18)#print "age is %d" % stu2.age# 报错: 'Student' object has no attribute 'set_age'#为了给所有实例都绑定方法,可以给class绑定方法:Student.set_age=MethodType(set_age,None,Student)stu2=Student("hello",80)stu2.set_age(18)print"age is %d"%stu2.age
#用tuple定义允许绑定的属性名称classPerson(object):__slots__=("name","age")p=Person()p.name="张三"print"name is %s"%p.namep.gender="男"print"gender is %s"%p.gender# p.gender="男" AttributeError: 'Person' object has no attribute 'gender'
classBook(object):@propertydefprice(self):returnself.__price@price.setterdefprice(self,price):self.__price=pricebook=Book()book.price=15.5print"price is %f"%book.price
#继承classAnimal(object):defrun(self):print"Animal is Running"classDog(Animal):passclassCat(Animal):passdefexecuteRun(animal):animal.run()executeRun(Dog())#判断一个变量是否是某个类型可以用isinstance()判断:printisinstance(Dog(),Animal)# True