知识点:
1.python 之 动态特性: 程序在运行的时候可以修改
2.动态添加对象属性 p1.xxx = "str" (p1为类(P)的实例对象)
3.动态添加对象方法
首先需要导入types模块 p1.xxx = types
定义函数 def xxx(self):
print("%s",self.xx)
添加 p1.xxx = types.MethodType(run,p1)#(函数名,对象名)
4.动态添加静态方法
定义静态函数
@staricmethod
def test():
print("xxxxxx")
P.test = test
5.动态添加类方法
定义类方法
@classmethod
def test(cls)
print(cls.xxx)
P.test = test
#动态添加对象属性
class P(object):
def __init__(self,name):
self.name = name
p1 = P("p1")
p1.age = 18
print(p1.age)
#动态添加对象方法
def run(self):
print("----%s正在跑--"%self.name)
#xxx = types.MethondType(run,p1) 也可以
p1.run = types.MethodType(run,p1) #(函数名,实例对象)
p1.run()
#动态添加类属性
#动态添加类方法
@classmethod
def prinNum(cls):
print("--class methed--P的weight %s-"%cls.weight)
P.prinNum = prinNum
P.prinNum()
#动态添加静态属性
#动态添加静态方法
@staticmethod
def prinStatic():
print("---static--method")
P.prinStatic = prinStatic
P.prinStatic()