文章来自《Python cookbook》.

翻译仅仅是为了个人学习,其它商业版权纠纷与此无关!

-- 61.182.251.106 [2004-11-21 02:13:53]

描述

Delegating Automatically as an Alternative to Inheritance

使用自动代理,代替继承

Credit: Alex Martelli

问题 Problem

You'd like to inherit from a built-in type, but you are using Python 2.1 (or earlier), or need a semantic detail of classic classes that would be lost by inheriting from a built-in type in Python 2.2. 希望继承内置类型,但是正在使用Python2.1及更早版本, 换句话说,继承python2.2中的内置类型会导致信息丢失?, 需要语义处理

解决 Solution

With Python 2.2, we can inherit directly from a built-in type. For example, we can subclass file with our own new-style class and override some methods:

python 2.2中,可以从内置类型继承,比如,可以继承file类,定义具有新形式的子类,覆盖一些方法:

   1 class UppercaseFile(file):
   2     def write(self, astring):
   3         return file.write(self, astring.upper(  ))
   4     def writelines(self, strings):
   5         return file.writelines(self, map(string.upper,strings))
   6 
   7 upperOpen = UppercaseFile

To open such a file, we can call upperOpen just like a function, with the same arguments as the built-in open function. Because we don't override _ _init_ _, we inherit file's arguments, which are the same as open's.

使用上面的文件,使用upperOpen既可以, 具有同内置函数open(file)一样的的参数列表. 由于并未覆盖init函数,这里继承了file类的参数,并且同open(file)的参数列表要求的意志.

If we are using Python 2.1 or earlier, or if we need a classic class for whatever purpose, we can use automatic delegation:

如果使用Python 2.1以及更早版本,或则出于某种目的需要使用旧形式的类?,可以使用自动代理:

   1 class UppercaseFile:
   2     # Initialization needs to be explicit
   3     def _ _init_ _(self, file):
   4         # NOT self.file=file, to avoid triggering _ _setattr_ _ 
   5         self._ _dict_ _['file'] = file
   6 
   7     # Overrides aren't very different from the inheritance case:
   8     def write(self, astring):
   9