python中动态特性的实现
2018-01-25 14:13
260 查看
python中一切皆对象,变量可以存储对象的地址
python动态语言的实现
为实例动态添加属性**
首先定义一个动物类代码如下:
输出如下结果
可见Animal这个类是没有sex这个属性的
下面实现添加,代码如下:
输出结果:
在输出结果中Animal类依旧是没有sex这个属性的
为实例添加方法
代码实现如下:
python动态语言的实现
为实例动态添加属性**
首先定义一个动物类代码如下:
class Animal (Object): name = '' age = 0 animal = Animal() print animal.name print animal.age print animal.sex
输出如下结果
Traceback (most recent call last): 0 File "/Users/mrrobot/Desktop/untitled/test.py", line 9, in <module> print test.sex AttributeError: 'Animal' object has no attribute 'sex'
可见Animal这个类是没有sex这个属性的
下面实现添加,代码如下:
#!/bin/env python class Animal(object): age = 0 name = '' animal =Animal() animal.sex = 'f'#只要直接在实例上添加属性便可以 #同样这种操作也可以对类使用 print animal.age print animal.name print animal.sex print dir(Animal)
输出结果:
0 f ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'age', 'name'] Process finished with exit code 0
在输出结果中Animal类依旧是没有sex这个属性的
#!/bin/env python class Animal(object): def init(self): self.age = 0 self.name = '' animal = Animal() animal.init() #只有在执行了init()方法后,animal才有age和name这两个属性, #否者会报'Animal' object has no attribute 'age'这个错, #这里的错误中的Animal值的是Class Animal print animal.age print animal.name
为实例添加方法
代码实现如下:
#!/bin/env python from types import MethodType class Animal(object): age = 0 name = '' animal =Animal() def set_age(self,age) : self.age=age animal.set_age = MethodType(set_age,animal,Animal) #通过types模块的MethodType将一个方法和一实例进行bounding(绑定) #如果想要将这个set_age()方法和这个类所有的实例相关联的话,可以将上面的animal换成None print animal.age animal.set_age(2) print animal.age
相关文章推荐
- Python实现动态添加类的属性或成员函数的解决方法
- 利用OpenGL特性抓取QML屏幕并实现其动态效果
- Py:Python实现好莱坞《黑客》影视中珠帘似吊炸天的华丽动态加密页面——Jason niu
- Python实现动态加载模块、类、函数的方法分析
- python动态语言特性小结
- 用Python实现动态的切换桌面背景
- 结合rpyc使用python实现动态升级的方法
- 流畅python学习笔记:第十九章:动态属性和特性
- 利用Objective-C的反射机制和运行时特性实现类静态方法的动态访问(二)
- 使用Spring特性实现接口多实现类的动态调用
- 输入参数能动态调决定调用哪个实现类 spring的一个特性
- python将logging模块封装成单独模块并实现动态切换Level
- 如何用Python,C#等语言去实现抓取静态网页+抓取动态网页+模拟登陆网站
- python实现对动态页面的某一页爬取
- python实现动态更新远程机器列表的SSH登录脚本
- Python实现web动态服务器
- Python中C++类特性的实现原理
- Python动态特性
- python中向类中动态添加新特性及删除属性方法
- python 实现斐波那契数列,动态删除历史数据demo,很久以前写的,分享给大家 推荐