您的位置:首页 > 编程语言 > Python开发

python中动态特性的实现

2018-01-25 14:13 260 查看
python中一切皆对象,变量可以存储对象的地址

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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: