Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Functions, Classes, and Objects

Writing Pythonic code

What is “Pythonic”?

Code is read much more often than it is written.

  • “Pythonic” means code that follows the conventions of the Python community. It is clean, readable, and concise.

  • PEP 8 is the official “Style Guide” for Python code. It’s like the grammar rules for the language.

Source: PEP 8 – Style Guide for Python Code

Output
The Zen of Python, by Tim Peters

Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

What is a Function?

A function is a block of organized, reusable code that performs a specific task.

  • DRY Principle: “Don’t Repeat Yourself.” If you find yourself copy-pasting code, you should probably make it a function.

  • Modularity: It breaks a complex problem (like “Process the Census”) into small, manageable pieces (e.g., “Clean Name”, “Calculate Age”, “Validate Address”).

Anatomy of a Function

  1. def keyword: Tells Python you are defining a function.

  2. function name: Follows snake_case rules (e.g., calculate_yield). Used to identify and call a function.

  3. parameters: The inputs the function needs (inside parentheses).

  4. docstring: A comment describing what the function does.

  5. return value: The output sent back to the main program.

Syntax

def function_name(parameter1, parameter2):
    """docstring: Explains what this does."""
    # Code block
    result = parameter1 + parameter2
    return result
Output
Magandang araw! Welcome to the Digital Census.

Parameters and Arguments

  • Parameter: The variable name in the function definition (e.g., area).

  • Argument: The actual value you pass when running it (e.g., 5.5).

We can also set Default Arguments. These are used if the user doesn’t provide a value.

Output
Output
Magandang araw Juan dela Cruz! Welcome to the Digital Census.
Output
Magandang araw Maria dela Cruz! Welcome to the Digital Census.

return vs. print

This is a common point of confusion.

  • print(): Displays text on the screen. The computer “forgets” it immediately.

  • return: Gives the value back to the program so you can store it in a variable.

Output
100
Stored from Print: None
Stored from Return: 100

Classes and Objects

Definitions

When used in the Object-Oriented paradigm:

  • Class: The blueprint or template; It defines what attributes and methods the objects created from the class will have (e.g., The definition of a “Farm”).

  • Object: A specific instance of a class that encapsulates/inherits the class’ attributes (data) and methods (behavior) (e.g., “Mang Juan’s Farm”).

  • Methods: Functions that the object can perform (e.g., Calculate Yield).

  • Attributes: Variables stored inside the object (e.g., Hectares, Crop Type).

Methods and attributes can both either be defined for the class or specific instance/object.

  • Class methods are bound to the class and not to a specific instance of a class making them useful as factory methods or for accessing class-level attributes.

  • Class attributes are shared by all instances of a class compared to instance attributes that are specific to one instance.

The __init__ Method

This is a special function that runs automatically when you create a new Object. We use it to set up the initial data.

Output
Maligaya Estate plants Palay on 10 hectares.

Overriding Methods (Polymorphism)

In Python, we can change how standard commands work for our custom objects.

For example, if you try to print(my_farm) right now, Python will give you a messy code like <__main__.Farm object at 0x00...>.

We can fix this by overriding the special __str__ method.

Output
<__main__.Farm object at 0x77d564306270>
Output
FARM: Maligaya Fields | CROP: Corn | AREA: 5 ha
Estimated Harvest: 22.5 tons

Practice Exercises

Creating a class

  1. Create a class Livestock.

  2. In the __init__ method, accept species (e.g., “Carabao”) and count (e.g., 4).

  3. Create an object called my_animals and print its species attribute.

Source
Carabao

Adding a class method

  1. Add a standard method called check_status().

    • If count < 20, return “Small Herd”.

    • Else, return “Commercial Herd”.

  2. Create several instances of Livestock and check their status.

Source
Commercial Herd
Small Herd

Overriding the print method

  1. Override the __str__ method to your Livestock class.

  2. It should return a string like: “Registered Herd: {count} heads of {species}”.

  3. Create an instance and pass it directly to the print() function to test it.

Source
Registered Herd: 10 heads of Carabao