3

I was testing inheritance of python, I've got this:

__metaclass__=type
class b:
    def __init__(s):
        s.hungry=True
    def eat(s):
        if(s.hungry):
            print "I'm hungry"
        else:
            print "I'm not hungry"
class d(b):
    def __init__(s):
        super(b,s).__init__()
    def __mysec__(s):
        print "secret!"

obj=d()
obj.eat()

There's runtime error as:

Traceback (most recent call last):
  File "2.py", line 17, in ?
    obj.eat()
  File "2.py", line 6, in eat
    if(s.hungry):
AttributeError: 'd' object has no attribute 'hungry'

I couldn't understand this, as the super class of "b" has s.hungry in its init, and the sub class calls "super" inside its own "init" Why still, python says "d" object has not attribute 'hungry'?

Another confusion: the error message treats "d" as an object, but I defined it as a class! Did I get anything wrong, how to make it work?

4
  • 1
    Use super on the current class, not the parent class. i.e. super(d, s).__init__() Commented Dec 24, 2016 at 6:16
  • Also, I highly recommend against using one-letter names in Python. I suggest reading through python.org/dev/peps/pep-0008 Commented Dec 24, 2016 at 6:16
  • super() in python3 is much simple, you do not need pass args. Commented Dec 24, 2016 at 6:22
  • A class is an object, a class instance of an object. Why are you overriding dunder init in d? -just remove it. Commented Dec 24, 2016 at 7:41

3 Answers 3

2
class d(b):
    def __init__(s):
        super(d,s).__init__()
    def __mysec__(s):
        print ("secret!")

Document:

For both use cases, a typical superclass call looks like this:

> class C(B):
>     def method(self, arg):
>         super(C, self).method(arg)
Sign up to request clarification or add additional context in comments.

Comments

2

I guess this is what you were looking for:

__metaclass__=type
class b:
    def __init__(self):
        self.hungry=True
    def eat(self):
        if(self.hungry):
            print "I'm hungry"
        else:
            print "I'm not hungry"
class d(b):
    def __init__(self):
        super(d,self).__init__()
    def __mysec__(self):
        print "secret!"

obj=d()
obj.eat()

Comments

0

I prefer to write the code for more clarity in python 3.x

class Base:
    def __init__(self):
        self.hungry=True

    def eat(self):
        if(self.hungry):
            print("I'm hungry")
        else:
            print("I'm not hungry")

class Derived(Base):
    def __init__(self):
        super().__init__() # this works
        # super(Derived,self).__init__() # this works
        # super(Base,self).__init__() # this doesn't work

>>> d=Derived()
>>> d.eat()
I'm hungry

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.