python的面向对象. 下面的代码涉及到了Python新类(new style class)中的诸多特性。 # abstract class class Base(object): def __init__(self): if self.__class__ is Base: raise NotImplementedError('Abstract class'); # base class class C(Base): # static private attribute # can only be accessed by using c._C__num __num = 100 def __init__(self): Base.__init__(self); # instance attribute self.name = '22'; def fun(self): print 'Fun from C' # inheritance class D(C): def __init__(self): #super(D, self).__init__(); C.__init__(self); def fun(self): C.fun(self); print 'Fun from D' @staticmethod def fun2(): print 'Static method from D' # mimic interface, it's a meta class # which can NOT be instantiated. class IDispose(type): def __init__(cls, name, bases, attrd): if '__del__' not in attrd: raise TypeError('Must implement __del__!'); # class implementing the interface class Foo(object): __metaclass__ = IDispose; def __del__(self): print 'Disposed!' # slot example class MySlot(object): # a substitude of __dict__, which costs quite some memory sometimes __slots__ = ('__name','addr') def __init__(self): self.name = '22'; def get_name(self): return self.__name; def set_name(self, value): self.__name = value; # removing set_name makes the property readonly name = property(get_name, set_name);