Sobes.tech
Junior — Middle

Can you explain the difference between a class and a function in programming?

sobes.tech AI

Answer from AI

A class and a function are different concepts in programming, especially in the object-oriented language Python.

  • Function — is a block of code that performs a specific task and can accept arguments and return a result. Functions help structure code and reuse logic.

  • Class — is a template for creating objects (instances), which combines data (attributes) and behavior (methods) into one structure. Classes allow modeling real entities and organizing code as objects.

Example:

# Function
def greet(name):
    return f"Hello, {name}!"

# Class
class Person:
    def __init__(self, name):
        self.name = name
    def greet(self):
        return f"Hello, {self.name}!"

# Usage
print(greet("Anya"))

p = Person("Ivan")
print(p.greet())

Thus, a function is simply an action, and a class is a structure that can contain functions (methods) and data.