python new-style class和old-stype class使用super的方式

阅读更多
#old-style class
class Base(): 
    def __init__(self, name): 
        self.name = name
   
class Child(Base): 
    def __init__(self,name): 
        Base.__init__(self,name)
        print self.name
Child('zs')

 

#new-style class
class Base(object): 
    def __init__(self, name): 
        self.name = name
  
class Child(Base): 
    def __init__(self,name): 
        super(Child, self).__init__(name)
        print self.name
Child('zs')

 

常见错误:

 

class Base(): 
    def __init__(self, name): 
        self.name = name
   
class Child(Base): 
    def __init__(self,name): 
        super(Child,self).__init__(self,name)  #old-style class不支持super,这里会报错“TypeError: must be type, not classobj”
        print self.name
        
Child('zs')

 

修正方式:

1. Base继承object,即修改为new-style class方式

2. 修改为old-style class方式,即第一个示例(去掉super)

 

-end

你可能感兴趣的:(python new-style class和old-stype class使用super的方式)