Amazing Python::Dynamic
第一次听说Python的时候就听到了它是一个动态语言,至于如何动态我实在想象不出来,最近才有所体会。这里我会给出一些小例子来演示这个动态的含义。
>>> class MyClass:
… pass
>>> inst = MyClass();
>>> inst.head = "hello"
>>> inst.head
‘hello’
>>> inst.face
Traceback (most recent call last):
File "<pyshell#6>", line 1, in -toplevel-
inst.face
AttributeError: MyClass instance has no attribute ‘face’
在MyClass中,根本没有任何属性的定义,而在下面MyClass的实例inst,我给了它一个属性head赋值“hello”,没有出错,也就是这里动态的定义了一个属性head。
而接下来访问inst.face,因为没有赋值语句,也就没有动态定义,所以返回错误。而这个head也仅仅属于inst而已,并没有加入到MyClass中去。
>>> dir(MyClass)
['__doc__', '__module__']
>>> dir(inst)
['__doc__', '__module__', 'head']
而由于动态类型得特性,使得Python中类型得定义变得很灵活,甚至有些随意,这就引起了很多人得怀疑,如此灵活得风格会严重得阻碍编写程序,并且很容易引起一个错误而很难发现。
那么看下面这个东西吧。
>>> from types import *>>> >>> def what (x):... if type(x) == IntType:... print "This is an int."... else:... print "This is something else."... >>> what(4)
This is an int.>>> >>> what("4")
This is something else.
事实上,静态类型得一个问题是,我们想要得类型常常不是能够立即可用得,而有时候我们甚至连想要什么类型都是无法实现确定得。于是我们可以发现很多时候我们要用到泛型算法,或者自己编写泛型。
而动态特性使得函数天然就是泛型,这些函数天生就可以应付各种类型的数据,就像上面得例子,what()会根据具体得类型的X给出想要的结果。就好像我们在C语言中写道:
#define max(a,b) ((a) > (b) ? (a) : (b))
当然我这里给出的列子没有什么实际的意义和轰动的效果,可能说服力不强,动态特性的优点也不仅于此。连Stanly Lippman都说过(去年11月份看的,如果我没记错的话):
“C++这样的静态语言在动态语言面前的反击是有限的”
那么Python的这一动态特性,绝不会像我说得那么简单了。
Trackback: http://tb.donews.net/TrackBack.aspx?PostId=334876


Recent Comments