使用super关键字,会按照继承顺序执行相应类中的方法,在没有多继承的情况下,一般是执行父类

# -*- coding: utf-8 -*-
#! /usr/bin/python



class Counter(object):
def __init__(self):
super(Counter,self).__setattr__("counter",0)

def __setattr__(self, key, value):
print 'emmm1',self.counter
super(Counter,self).__setattr__("counter",self.counter+1)
print 'emmm2',self.counter
super(Counter, self).__setattr__(key,value)
print 'emmm3',self.counter

def __delattr__(self, item):
print self.counter
self.counter -=1
print self.counter
super(Counter,self).__delattr__(item)

c=Counter()
c.x=1
c.y=1
del c.x

打印结果

emmm1 0
emmm2 1
emmm3 1
emmm1 1
emmm2 2
emmm3 2
2
emmm1 2
emmm2 3
emmm3 1
1

思路分析

第一步,执行c=Counter()
【Python】super关键字用法_python第二步,执行c.x=1

【Python】super关键字用法_python_02第三步,执行c.y=1
【Python】super关键字用法_父类_03最后1步,执行del c.x

【Python】super关键字用法_python_04