首页 > 编程语言 > 详细

Python 之动态添加属性以及方法

时间:2019-05-11 19:53:11      阅读:132      评论:0      收藏:0      [点我收藏+]
import types


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

def run(self):
    print("%s is running..." % self.name)

# 静态方法
@staticmethod
def test():
    print("static method...")

# 类方法
@classmethod
def eat(cls):
    print("class method...")

if __name__ == "__main__":
    p = Person(yy, 18)
    # 给person类添加一个属性
    p.id = 12;

    # 给person类添加一个方法
    p.run = run
    p.run(p)
    # 方式二
    p.run = types.MethodType(run, p)
    p.run()

    # 给person类添加一个静态方法
    Person.test = test
    Person.test()

    # 给person类添加一个类方法
    Person.eat = eat
    Person.eat()
    print(dir(p))

 

Python 之动态添加属性以及方法

原文:https://www.cnblogs.com/yang-2018/p/10849750.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!