More on __init__() and self


#1



https://www.codecademy.com/courses/python-intermediate-en-WL8e4/1/1?curriculum_id=4f89dab3d788890003000096#


Oops, try again.
Did you add the is_hungry attribute to init()?
Well duh, I did.


# Class definition
class Animal(object):
    """Makes cute animals."""
    # For initializing our instance objects
def __init__(self, name, age, is_hungry):
    self.name = name
    self.age = age
    self.is_hungry = is_hungry
# Note that self is only used in the __init__()
# function definition; we don't need to pass it
# to our instance objects.

zebra = Animal("Jeffrey", 2, True)
giraffe = Animal("Bruce", 1, False)
panda = Animal("Chad", 7, True)

print zebra.name, zebra.age, zebra.is_hungry
print giraffe.name, giraffe.age, giraffe.is_hungry
print panda.name, panda.age, panda.is_hungry


#2

Perhaps you should bring your code to a runnable state?


#3

Uh...W-what...? :confused:


#4

Run your code. Does it behave as you intend? I imagine not, it crashes. So, debug it.

If you don't know what's missing/wrong about the code, observe what it does and compare to what it's meant to do! Yours is pretty far off, so it should be evident what you need to fix.


#5

...Yeah. But my question is, how?
I don't know how (that's the reason I'm here)


#6

That's a different question entirely though, right?

Start by identifying what it does wrong. Then study the error message / the part responsible for that behaviour.

I'll help you along but I'll only give you what you seem to be missing right at the moment, pointing at the next thing to consider.


#7

Hmm well it says in whatever that console thing is called

Traceback (most recent call last):
  File "python", line 13, in <module>
TypeError: object.__new__() takes no parameters

What is new? I don't see new.


#8

You tried to call object's constructor with arguments, but that constructor does not accept any arguments.
Your class needs to implement its own __init__ to handle those arguments. If you do not create that method, then the parent class's one gets called in its stead. The parent class of your class is object

If not implementing your own __init__ passes the call on to the parent class, and the call was passed on to the parent class, what conclusion can you draw?


#9

I'm really dumb I still don't get a word you're saying.


#10

Nvm. Solved it. was that my init function wasn't indented.


#11

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.