AITC Wiki

Python Functions and Classes

Python 函数与类

Python Functions and Classes

中文版:Python 函数与类

Functions encapsulate reusable logic; classes provide the foundation for object-oriented programming in Python.

Functions

A user-defined function is a block of organized, reusable code defined by the programmer rather than being built into the language. Functions help break down larger programs into smaller, more manageable, and logical units.

Defining Functions

# Function to add two numbers
def add(x, y):
    return x + y
 
result = add(5, 3)
print("5 + 3 =", result)  # 8

Default Parameters

def greet(name="Guest"):
    print("Hello,", name)
 
greet("Alice")  # Hello, Alice
greet()         # Hello, Guest

Classes

Classes are a fundamental building block of object-oriented programming (OOP) in Python. A class defines attributes and methods that its instances (objects) will have.

Defining a Class

class Dog:
    def __init__(self, name, age):
        self.name = name  # Constructor initializes instance attributes
        self.age = age
 
    def bark(self):
        print(f"{self.name} says woof!")
 
# Create an object/instance
my_dog = Dog('XiaoHuang', 2)
print('my dog name is', my_dog.name)   # my dog name is XiaoHuang
print('my dog age is', my_dog.age)     # my dog age is 2
my_dog.bark()  # Output: XiaoHuang says woof!

Common Misconceptions

  • Forgetting self: In class methods, self must be the first parameter to access instance attributes.
  • Modifying mutable default arguments: Default mutable arguments (like lists) are shared across function calls.

Sources