Abstract in Python
Python does not support the abstract in syntax level. However, there’re many solutions, Python IAQ, and here (in Chinese). However, I don’t like them because lack of aesthetic. And I found a way by using the python decorator syntax.
Python没有在语法层面上对抽象类,抽象方法提供支持。但有很多方法绕过了这一阻碍。例如很偏门的Python IAQ,以及粲言堂。但我不喜欢这些解决方案,我不喜欢这些解决方案因为它们缺少美感。因此,我找到了一个利用Python修饰器来实现抽象类、抽象方法。
Here’s the sample code for abstract class,
def abstract(cls):
if hasattr(cls, '__init__'):
method = getattr(cls, '__init__')
else:
method = None
def init_method(self, *argv):
if self.__class__ == cls:
raise NotImplementedError('abstract method')
if method:
method(self, *argv)
setattr(cls, '__init__', init_method)
return cls
Now it’s quite easy to use it,
@abstract class Foo(object): pass class Bar(Foo): pass
Decorator is a normal method which accept at least 1 arg. It can apply on class or method. It will change the being defined class or method to the return value. So when decorating a class, the return value should be the class itself in most case. And we need to remember the decorated object is not defined, just still processing. So the member method of class is still a function object, not linked to the class yet. So we can’t retrieve the class trait from it.
简单的说,Decorator就是任何一个接收至少一个参数的方法。以@的形式应用在类和方法上。通过应用Decorator,把类或方法的定义修改成这个Decorator方法的返回值。因此,当我们需要修饰一个类的时候,应当返回这个类本身。因为通常我们修改一个类,是想在这个类上添加新的类属性和类方法,而非是需要重新定义一个新类。此外,还有一点值得注意,那就是在运行Decorator的时候,这个定义还没有完成,因此,任何被修饰的类方法只是一个普通的function对象,尚未连接到它所属的类上去。也就是说,我们无法从这个function对象上得到所属类的信息。
Unrelated Posts
on March 10th, 2010 | No Comments »

Leave a Reply