python基础教程:Python实现动态给类和对象添加属性和方法操作示例

Pamela ·
更新时间:2024-09-20
· 736 次阅读

本文实例讲述了Python实现动态给类和对象添加属性和方法操作。分享给大家供大家参考,具体如下:

动态给类和对象添加属性

定义一个Person类

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

给对象添加属性

# 创建2个Person,分别为p1,p2 p1 = Person('amy') print(p1.name) p1.age = 10 # 给p1对象添加属性 print(p1.age) # 输出10 p2 = Person('anne') print(p2.name) p2.age = 18 # 给p2对象添加属性 print(p2.age) # 输出18

运行结果:

amy 10 anne 18

给类添加属性

p1 = Person('amy') p2 = Person('anne') Person.sex = 'female' print(p1.sex) # 输出 female print(p2.sex) # 输出 female p2.sex = 'male' print(p2.sex) # 输出 male

运行结果:

female female male

动态给类和对象添加方法

动态给类添加方法

# 在类的外部定义一个sleep函数 p1 = Person('amy') p2 = Person('anne') def sleep(self): print('%s sleep' % (self.name)) Person.sleep = sleep Person.sleep(p1) # 输出 amy sleep Person.sleep(p2) # 输出 anne sleep

运行结果:

amy sleep anne sleep

给对象添加方法

import types # 如果是给对象动态添加方法,需要导入types模块 p = Person('amy') def eat(self): print('%s eat' % (self.name)) p.eat = types.MethodType(eat, p) # 调用MethodType()函数,参数1:方法名,参数2:对象名 p.eat() # 输出 amy eat

运行结果:

amy eat

最后给大家推荐一个资源很全的python学习聚集地,[点击进入],这里有我收集以前学习心得,学习笔记,还有一线企业的工作经验,且给大定on零基础到项目实战的资料,大家也可以在下方,留言,把不懂的提出来,大家一起学习进步


作者:程序员吉塔



python基础 python基础教程 示例 方法 属性 对象 类和对象 动态 Python 教程

需要 登录 后方可回复, 如果你还没有账号请 注册新账号