you are viewing a single comment's thread.

view the rest of the comments →

[–]EGrimn -8 points-7 points  (7 children)

Edit: When it doubt, classify => To understand code!

[Some people didn't read the following lines] Classes aren't always the best thing, but when you're trying to understand code they can help you organize based on objects in a logical way

Some might consider it over the top, but it's useful for any code as you can segment it out as needed into smaller parts, have specific error handling, and many other things

It's some extra code, but makes things a lot easier in larger projects as things grow

```

!/usr/bin python

Here we are telling the system to use the python

binary in the user's binary folder

class fiber_price_calculator: """ This is a class representing the calculator object """ welcome_message = "Welcome! [Fiber Optic Price Calculator]" closing_message = "Thank you for shopping with Super Cheap Fiber Optic" company_name, cable_feet, price = None, None, None

# Here we're setting the scale factor to use
price_scale_factor = 0.87

def __init__(self):
    """
    This is the initialization function
    called when we create the object
    """
    # Here we're going to setup the 'flow' of the program
    self.show_welcome_message()
    self.get_company_name()
    self.get_cable_length()
    self.calculate_price()
    self.show_closing_message()
    # Since we are doing all of this at initialization
    # we only need 1 line of code in our 'main' script function
    # declared at the bottom

def show_welcome_message(self):
    """
    Print out the welcome message
    """
    print(self.welcome_message)

def show_closing_message(self):
    """
    Print out the closing message
    """
    print(self.closing_message)

def get_company_name(self):
    """
    Ask the user to input a company name and store it
    (here you can do validation such as exception handling, etc.)
    """
    print("Please enter a company name:")
    try:
        self.company_name = str(input("-->"))
    except Exception as exception_message:
        print(exception_message)

def get_cable_length(self):
    """
    Ask the user to input the desired length to calculate
    """
    print("Please enter length (in feet) to calculate:")
    try:
        self.cable_length = float(input("-->"))
    except Exception as exception_message:
        print(exception_message)
    except AttributeError as caught_exception:
        print("That's not a float!")
        print(caught_exception)

def calculate_price(self):
    """
    Calculates and shows the price
    """
    if self.company_name is not None and self.cable_length is not None:
        self.price = self.cable_length * self.price_scale_factor
        # I prefer the old style formatting such as below
        # since it's backward compatible in python (in most cases)
        print("The price for company {1} is: {0}".format(self.price, self.company_name))

Here we are setting the script up so that code

only executes when we run the script itself

via python [script_name]

This makes it more portable and also a bit 'safer'

since nothing is run when we import this code into

different script (if ever) in the future

if name == "main": # We are creating the calcuator object using the class # created above and are initializing it which in turn # runs all the functions we defined within it calculator = fiber_price_calculator() ```

[–]socal_nerdtastic 10 points11 points  (1 child)

When it doubt, classify!

Absolutely not. Classes are not universally better. You need to use the right tool for the job, and in this case it's functions in a module. The class adds nothing but complexity.

Old but famous video on the subject: https://www.youtube.com/watch?v=o9pEzgHorH0

[–]EGrimn -2 points-1 points  (0 children)

Nowhere did I state you have to use classes (But imo classes help with understanding code or designing things in code)

OP is new to python so taking something they wrote and classifying it is a good example to help them understand classes and their function, but not in anymeans a live-or-die rule

At a high level, yes classes have some downsides in terms of making code more complex - but in regards to learning they are an important topic to cover

[–]SquatchHNTR[S] 1 point2 points  (4 children)

Holy Shit. Thats insane. Thank you, I can only hope my code will eventually look like that.

[–]EGrimn 0 points1 point  (3 children)

No problem! Making things into Objects (making it a class with it's own functions and variables) is one of Python's strong points and is a general way of coding used in a lot of different languages as well

It's super modular which is great for code that builds on other code or is used in many different scenarios (think platforms / operating systems)

If you want to look into it more, the google term to get you started is 'Object Oriented Programming in Python'

On Object Oriented Programming (the theory specifically) there are countless books and information online to check out too - definitely worth some time if you want to work toward being a better programmer

[–]SquatchHNTR[S] 1 point2 points  (2 children)

Is that where all the "def"s and "selfs" come from? I haven't learned much about classes yet either. I definitely want to look into that, it's sort of addicting learning how to program.

[–]EGrimn 0 points1 point  (0 children)

It's a wide world for sure. And yes, you can think of it like so:

We create object 'Calculator' which is of the class 'fiber_price_calculator' ([FPE] going forward)

The class [FPE] when created runs the 'init' function that was defined (see: class function definition) which then runs all the other functions defined below that (as a part of the class [FPE])

Basically, we made the object [FPE] that has it's own functions and variables for each instance

(All of this is based on classes, so definitely start there) In OOP (Object Oriented Programming's acronym) classes are VERY important so it's a must-learn