python的动态添加属性和方法

import types 

如果一个类已经写好  要想动态的添加一新的方法  那么需要用下面方法:

p1.eat = types.MethodType(eat,p1)    //即把eat函数动态绑定到了p1对象上

p1.eat()即可调用

@staticmethod

def test():

     xxxx

Person.test=test   动态添加一个静态方法给一个已经写好的类

不想让别人添加属性的话 可以在类中使用————__slots__=("name","age")   规定只允许添加name 和age 

猜你喜欢

转载自blog.csdn.net/IT_NEU_Lee/article/details/84575663