正是Charon的回复,让我觉得认真的学习一下Python method调用时候的是如何查找method的。结果不看不知道,一看下一跳,原来我原来关于python open class的想法是错误的。为什么是错误的呢?
先看看Ruby的Open class是怎么实现的。引用
Reading further on Ruby's object-oriented features, I found out in Programming Ruby that:
Classes are never closed: you can always add methods to an existing class. This applies to the classes you write as well as the standard, built-in classes. All you have to do is open up a class definition for an existing class, and the new contents you specify will be added to whatever's there.
As a conseguence, you can always revise a method (changing its semantics) to an existing class no matter where you are. For instance, let consider the following example.
可以看出Ruby的Open Class是基于声明的。你在类定义的时候就改变了其方法或者Attribute的sematic.
然而Python中是在运行时改变的,应该不能成为Open class或者可以叫做Open object:).当然这个称呼是不恰当的。或许有人会居然python可以实现和ruby Open Class一样的功能,为何还要在乎概念呢。
有两个理由:
Python中实现类似于Ruby Open Class的功能其实是Python把Function做为一等公民的另外一种表现,而不是所谓的Open Class.
为了介绍Python中Method与Function的差别,那样就可以更好的说明Charon前面试图说明的东西。
Python的Instance Object包含了data attributes & methods, data attributes好理解,那么Methods呢?Methods是该实例变量的类中定义的Functions.为什么要要强调这个呢?因为在Method和Function的调用过程中存在着以下差别。当你调用Function的时候,Function接受的参数就是你传递的参数。而当你调用Method的时候,实际参数是你传入的参数和instance object的引用,示例代码如下: