首先申明下,本文为笔者学习《Python学习手册》的笔记,并加入笔者自己的理解和归纳总结。
1、实现继承,在类名后面的括号内加入需要继承的类。
Circle类继承了Shape类,同时继承了变量、构造函数和其他方法。 >>> class Shape: def __init__(self, x, y, w=10, h=10): self.x = x self.y = y self.width = w self.height = h def draw(self): print "Shape draw" >>> class Circle(Shape): pass 调用Circle类 >>> c = Circle(50, 65) # Circle继承了Shape的构造函数和属性 >>> c.__dict__ {'y': 65, 'x': 50, 'height': 10, 'width': 10} >>> c.draw() # Circle继承了Shape的draw方法 Shape draw2、方法覆盖。
覆盖Circle的构造函数和draw方法。 >>> class Circle(Shape): def __init__(self, x, y, radius=10): Shape.__init__(self, x, y, 0, 0) self.radius = radius def draw(self): print "Circle draw" >>> c = Circle(50, 65) # 调用Circle的构造函数 >>> c.__dict__ {'y': 65, 'x': 50, 'height': 0, 'radius': 10, 'width': 0} >>> c = Circle(50, 65, 20) >>> c.__dict__ {'y': 65, 'x': 50, 'height': 0, 'radius': 20, 'width': 0} >>> c = Circle(50, 65, 20, 20) Traceback (most recent call last): File "<pyshell#188>", line 1, in <module> c = Circle(50, 65, 20, 20) TypeError: __init__() takes at most 4 arguments (5 given) >>> c.draw() # 调用Shape的draw方法 Circle draw3、方法调用顺序。
Sampe有两个父类Sup1和Sup2。查找顺序Sample->Sup1->Sup2。 Sup1和Sup2是根据在Sample继承顺序排列的。 >>> class Sup1: def fun(self): print "Sup1.fun" def fun1(self): print "Sup1.fun1" >>> class Sup2: def fun(self): print "Sup2.fun" def fun1(self): print "Sup2.fun1" def fun2(self): print "Sup2.fun2" >>> class Sample(Sup1, Sup2): def fun(self): print "Sample.fun" >>> s = Sample() >>> s.fun() # 调用Sample自身的fun方法 Sample.fun >>> s.fun1() # 调用Sup1的fun1方法 Sup1.fun1 >>> s.fun2() # 调用Sup2的fun2方法 Sup2.fun24、抽象类
>>> from abc import ABCMeta, abstractmethod >>> class Super: __metaclass__ = ABCMeta # metaclass设置为ABCMeta @abstractmethod # 方法添加abstractmethod def fun(self): pass >>> Super() Traceback (most recent call last): File "<pyshell#46>", line 1, in <module> Super() TypeError: Can't instantiate abstract class Super with abstract methods fun >>> class Sample(Super): def fun(self): print "in sample" >>> Sample().fun() in sample5、特殊变量
>>> class Sample: def __init__(self): self._x = 12 self.__x = 13 def fun(self): print "fun" def _fun(self): print "_fun" def __fun(self): print "__fun" >>> s = Sample() >>> dir(s) # __x和__fun变成_Sample__xx ['_Sample__fun', '_Sample__x', '__doc__', '__init__', '__module__', '_fun', '_x', 'fun']6、限定属性__slots__
>>> class Sample(object): # 定义一个继承object的类 __slots__ = ("name", "age") # __slots__定义了两个属性 >>> s = Sample() >>> s.name = "Mike" # 可以进行属性name >>> s.name 'Mike' >>> s.addr = "ShangHai" # addr没有定义,无法访问 Traceback (most recent call last): File "<pyshell#216>", line 1, in <module> s.addr = "ShangHai" AttributeError: 'Sample' object has no attribute 'addr'