为什么我的类不从父类继承?

时间:2015-06-17 09:51:25

标签: python class inheritance metaclass

我正在创建一个子类,但是我很难从父类继承:

def ParentClass(object):

    def __init__(self,num):
        self.num = num
        self.get_soup()

    def get_soup(self):
        self.soup = 'soup'
        return self.soup

def SubClass(Advert):

    def __init__(self,num):
        ParentClass.__init__(self,num)

    def test(self):
        print 'it works'
        print self.num

if __name__== "__main__":

    num = 1118868465    
    ad = SubClass(num)
    ad.test()

我应该查看元类吗?

1 个答案:

答案 0 :(得分:1)

您的代码中的函数不是类,父类也称为ParentClass而不是广告:

class  ParentClass(object): # class not def
    def __init__(self,num):
        self.num = num
        self.get_soup()

    def get_soup(self):
        self.soup = 'soup'
        return self.soup

class SubClass(ParentClass): # inherit from ParentClass
    def __init__(self, num):
        super(SubClass, self).__init__(num)
    def test(self):
        print 'it works'
        print self.num

您可能希望阅读this教程