Introduction to Classes Question: __init__()


#1



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


Hi everyone! I hope you've been enjoying the week so far. I just have a question about the introduction to classes code used. The following code works according to codecademy:

class Customer(object):
    """Produces objects that represent customers."""
    def __init__(self, customer_id):
        self.customer_id = customer_id

    def display_cart(self):
        print "I'm a string that stands in for the contents of your shopping cart!"

class ReturningCustomer(Customer):
    """For customers of the repeat variety."""
    def display_order_history(self):
        print "I'm a string that stands in for your order history!"

monty_python = ReturningCustomer("ID: 12345")
monty_python.display_cart()
monty_python.display_order_history()

However, what I'd like to know is why the class ReturningCustomer need not init(self, customer_id) like the class Customer. This is especially interesting for me because I went onto the next exercise, then saw that the code below worked for the "Inheritance Syntax" exercise:

class Shape(object):
    """Makes shapes!"""
    def __init__(self, number_of_sides):
        self.number_of_sides = number_of_sides

# Add your Triangle class below!
class Triangle(Shape):
    def __init__(self, side1, side2, side3):
        self.side1 = side1
        self.side2 = side2
        self.side3 = side3

As you can see, the class Triangle needed to use init() (be initialized?). Again, what I'd like to know is why the class ReturningCustomer need not init(self, customer_id) like the class Customer, but the Triangle class is doing essentially the same thing, but needs init(). Thank you very much for your time, and enjoy the weekend!


#2

need is not the right term, it depends on the purpose of your program. If a class (like ReturningCustomer) doesn't have an __init__() method, the parent init method is called instead

in case of triangle we overwrite __init__() because the init of Shape doesn't fit our purpose


#3

I see now. This makes a lot of sense! Thanks for your quick reply, and enjoy the rest of the week!


#4

and a class doesn't have to have an init method

init is just a method which is automatically called when you create a class instance (monty_python)


#5

I think I understand. Thanks for the reply!


#6

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