Introduction to Classes Question: __init__()


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")

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!


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


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


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)


I think I understand. Thanks for the reply!


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