Super()不起作用

时间:2018-04-18 23:30:55

标签: python-3.x

我的Parent类有一只猫和一只狗,我需要狗在cat类中执行一个函数。

此外,猫和狗需要是父类内部的内部嵌套类。

我读到狗需要使用super()来调用父类,然后使用他的cat实例。但它不起作用。

我收到错误

TypeError: super(type, obj): obj must be an instance or subtype of type

_

Animal = Parent()
Animal.ThisDog.BarkToCat()

class Parent(object):   

    def __init__(self, *args, **kwargs):
        self.ThisCat = self.cat()
        self.ThisDog = self.dog()

    class cat(object):
        def barked(self):
            return ("I better run!")

    class dog(object):
        def BarkToCat(self):
            print(super(Parent,self).ThisCat.barked())

我不会写狗(父母)

class dog(Parent):
    def BarkToCat(self):
        print(super(Parent,self).ThisCat.barked())

...因为我收到了错误

NameError: name 'Parent' is not defined

我输了。这是如何在Python中完成的?

2 个答案:

答案 0 :(得分:0)

这是一个嵌套类的示例,并显式链接外部类和嵌套类的实例。没有魔力。

class Parent(object):

    def __init__(self, name):
        self.name = name
        self.dog = self.adopt_dog()

    def walk(self):
        print('%s walks, and %s goes %s' % (
            self.name, self.dog.name, self.dog.bark()))

    def adopt_dog(self):
        # Refer to an attrubute of the class Parent,
        # which happens to be another class, Dog.
        return self.__class__.Dog(self, '%s\'s dog' % self.name)

    # Now the namespaced class.

    class Dog(object):
        def __init__(self, master, name):
            self.master = master
            self.name = name

        def bark(self):
            return 'bark!'

试一试:

>>> joe = Parent('Joe')
>>> joe.walk()
Joe walks, and Joe's dog goes bark!
>>> joe.dog.master is joe
True
>>> _

答案 1 :(得分:0)

我找到了让猫与狗互相交谈的方法,这就是让父母在狗和猫里面显而易见

class HasParent(object):
    def __init__(self, Parent=None):
        if (Parent is None):
            raise Exception("I need a parent!")
        self.Parent=Parent

class Parent(object):   

    def __init__(self):
        self.ThisCat = self.cat(Parent = self)
        self.ThisDog = self.dog(Parent = self)

    class cat(HasParent):

        def barked(self):
            return ("I better run!")

    class dog(HasParent):

        def BarkToCat(self):
            print(self.Parent.ThisCat.barked())


Animal = Parent()
Animal.ThisDog.BarkToCat()