本文实例讲述了Python实现动态添加属性和方法操作。分享给大家供大家参考,具体如下:
# -*- coding:utf-8 -*- #!python3 class Person(): def __init__(self, name, age): self.name = name self.age = age p1 = Person('ff', '28') print(p1.name, p1.age) # 给实例对象动态添加sex属性 p1.sex = 'female' print(p1.sex) # 给类动态添加属性 Person.height = None print(Person.height) p1.height = '155' print(p1.height) # 动态定义一个方法 def run(self, speed): print('run with %d speed' % speed) # 给实例绑定方法 import types p1.run = types.MethodType(run, p1) p1.run(30) # Person.run = run # 运行错误 # Person.run(4) @classmethod def run2(a, speed): print('run with %d m/s' % speed) # 给类动态绑定方法 Person.run2 = run2 # 给类绑定的方法, 需加修饰器 @classmethod, 标定其为类方法,可被类添加 Person.run2(4) p1.run2(5) # 类的实例对象也可调用类动态添加的方法 @staticmethod def eat(): print('eat---') Person.eat = eat # 类可添加静态方法, 定义静态方法时,需加修饰器@staticmethod Person.eat() p1.eat() # 实例对象同样可调用类动态添加的静态方法 del p1.name # del 删除属性 delattr(p1, 'sex') print(p1.name, p1.sex)
运行结果:
ff 28
female
None
155
run with 30 speed
run with 4 m/s
run with 5 m/s
eat---
eat---
Traceback (most recent call last):
File "/home/python/Desktop/test/12_动态语言.py", line 41, in <module>
print(p1.name, p1.sex)
AttributeError: 'Person' object has no attribute 'name'
更多关于Python相关内容感兴趣的读者可查看本站专题:《Python面向对象程序设计入门与进阶教程》、《Python数据结构与算法教程》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python编码操作技巧总结》及《Python入门与进阶经典教程》
希望本文所述对大家Python程序设计有所帮助。
华山资源网 Design By www.eoogi.com
广告合作:本站广告合作请联系QQ:858582 申请时备注:广告合作(否则不回)
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
免责声明:本站资源来自互联网收集,仅供用于学习和交流,请遵循相关法律法规,本站一切资源不代表本站立场,如有侵权、后门、不妥请联系本站删除!
华山资源网 Design By www.eoogi.com
暂无评论...
更新日志
2024年09月23日
2024年09月23日
- 金池刘罡《昨日情歌HQ》头版限量编号[低速原抓WAV+CUE]
- 段奥娟.2024-23·岁碎念【白米范】【FLAC分轨】
- 顺子.2001-昨日·唯一·更多·顺子自选辑【魔岩】【WAV+CUE】
- 无印良品.1999-私藏三首·原创相对论(EP)【滚石】【WAV+CUE】
- Merryland《Merryland》[FLAC/分轨][170.22MB]
- 庄锭欣 ELKIE《没有你的未来》[320K/MP3][15.78MB]
- 庄锭欣 ELKIE《没有你的未来》[FLAC/分轨][36MB]
- TchaikovskySwanLake,Op.20柴可夫斯基天鹅湖(2013)SACD[Hi-Res]
- 24bit达人艺典《琴歌终极版》整轨WAV+CUE
- 黑鸭子.2005-《发烧DSD》柏菲[WAV分轨]
- 群星.1990-电影看板·人间道【宝丽金】【WAV+CUE】
- 周殷廷.2024-TO.WHOM.IT.MAY.CONCERN【环球】【FLAC分轨】
- 草蜢.1997-三人世界精选17首【宝丽金】【WAV+CUE】
- 【古琴音乐】管平湖《广陵散》2004[FLAC+CUE]
- 【中国民乐】《少数民族器乐·苗岭的早晨》2004[WAV+CUE]