python3基础--- 动态添加属性和方法

import types

class Person(object):
    def __init__(self,newName):
        self.name = newName

p1 = Person("haha")
p1.age = 10
print('-----%d'%(p1.age))
Person.age = 100
p2 = Person('tom')
print('-----%d'%(p2.age))

#动态添加方法
# 1.import types
# 2.type.method(function,instance)
def run(self):
    print("-------run------")

p2.run = types.MethodType(run, p2)
p2.run()

#动态添加静态方法
@staticmethod
def func_static():
    print('----func_static-----')

Person.func_static = func_static
Person.func_static()

#动态添加类方法
@classmethod
def func_cls(cls):
    print('----func_cls-----')

Person.func_cls = func_cls
Person.func_cls()
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容