本文实例讲述了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相关内容感兴趣的读者可查看本站专题:《Python面向对象程序设计入门与进阶教程》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》及《Python入门与进阶经典教程》
希望本文所述对大家Python程序设计有所帮助。
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。