# Nakafa Framework: LLM URL: https://nakafa.com/en/subject/university/bachelor/ai-ds/ai-programming/everything-object-python Source: https://raw.githubusercontent.com/nakafaai/nakafa.com/refs/heads/main/packages/contents/subject/university/bachelor/ai-ds/ai-programming/everything-object-python/en.mdx Output docs content for large language models. --- export const metadata = { title: "Everything is an Object in Python", description: "Discover Python's object-oriented nature with hands-on examples. Explore how numbers, strings, lists, functions become objects with methods and attributes.", authors: [{ name: "Nabil Akbarazzima Fatih" }], date: "07/26/2025", subject: "AI Programming", }; ## Basic Object-Oriented Programming Concepts Python is a programming language that adopts the object-oriented programming or OOP paradigm. One of Python's fundamental principles is that everything is an object. This concept might sound abstract at first, but it's actually very natural and similar to how we view the real world. Imagine the world around us. All objects have characteristics and can do something. A car has color, brand, and speed, and can move, stop, and honk its horn. Similarly in Python, every data and function is an object that has attributes and can perform certain actions. ## Programming Paradigm Comparison ### Procedural Languages In procedural programming languages, state and actions are separated. Data and functions that operate on that data are separate from each other. max <= ps->occ) { return -1; } ps->occ++; return 0; } void leave(struct ParkSystem* ps) { if (ps->occ > 0) { ps->occ--; } } int main() { struct ParkSystem ps = {100, 0}; occupy(&ps); printf("%d %d", ps.max, ps.occ); return 0; }` }]} /> In the procedural approach, you can see that data (struct) and functions are separate. Functions accept data as parameters and modify them from outside. ### Object-Oriented Languages In object-oriented programming languages, state and actions are combined into one unit called a class. Attributes describe state, while methods describe actions that can be performed on that state. 0: self.occ -= 1 # Usage ps = ParkSystem(100) ps.occupy() print(f"Max: {ps.max}, Occupied: {ps.occ}")` }]} /> In the object-oriented approach, data and functions that operate on that data are packaged in one unit. Objects have the responsibility to manage their own state. ## Parking System as an Analogy Let's use a parking system as an example to understand the concept of objects. In the real world, a parking system has characteristics like maximum capacity and number of occupied spaces. This system can also perform actions like accepting cars entering or leaving. = self.capacity: return f"Parking full! Cannot park {vehicle_plate}" self.vehicles.append(vehicle_plate) self.occupied += 1 return f"Vehicle {vehicle_plate} successfully parked" def exit_vehicle(self, vehicle_plate): """Method to exit parking""" if vehicle_plate in self.vehicles: self.vehicles.remove(vehicle_plate) self.occupied -= 1 return f"Vehicle {vehicle_plate} exited parking" else: return f"Vehicle {vehicle_plate} not found" def get_status(self): """Method to view parking status""" available = self.capacity - self.occupied return { 'capacity': self.capacity, 'occupied': self.occupied, 'available': available, 'vehicles': self.vehicles } def is_full(self): """Method to check if parking is full""" return self.occupied >= self.capacity # Example usage parking = ParkingSystem(5) print(parking.park_vehicle("B 1234 CD")) print(parking.park_vehicle("B 5678 EF")) print(parking.get_status()) print(parking.is_full())` }]} /> ## Object Concepts in Data Types In Python, the concept of "everything is an object" means every data you create has attributes and methods. Let's explore this concept deeper. ### Numbers are Objects print(dir(result)) # View all available methods` }]} /> ### Strings are Objects ### Lists are Objects ### Dictionaries are Objects = 80} print(passed) # Nested dictionary university = { "students": { "CS": ["Alice", "Bob"], "Math": ["Charlie", "Diana"] }, "location": "Jakarta" } print(university["students"]["CS"])` }]} /> ## Functions are Also Objects One interesting thing about Python is that functions are also objects. This allows you to treat functions like regular data. # Functions can be stored in variables my_function = greet print(my_function("Alice")) # Hello, Alice! # Functions can be stored in lists functions = [greet, farewell] for func in functions: print(func("Bob")) # Functions can be used as parameters def call_function(func, name): return func(name) result = call_function(greet, "Charlie") print(result) # Functions can be returned from other functions def get_greeting_function(language): def english_greet(name): return f"Hello, {name}!" def indonesian_greet(name): return f"Halo, {name}!" if language == "english": return english_greet else: return indonesian_greet # Using returned function greet_func = get_greeting_function("indonesian") print(greet_func("Diana")) # Halo, Diana! # Lambda functions are also objects square = lambda x: x ** 2 print(type(square)) # print(square(5)) # 25` }]} /> ## Classes and Instances as Objects A class is a blueprint for creating objects, while an instance is an object created from that class. print(Student.__name__) # Student print(Student.university) # University of Indonesia` }]} /> ## Special Methods Python has special methods that start and end with double underscores. These methods allow your objects to behave like built-in types. 0: self.balance += amount return self def __sub__(self, amount): """Subtract balance (withdraw)""" if isinstance(amount, (int, float)) and amount > 0: if amount <= self.balance: self.balance -= amount else: print("Insufficient balance!") return self def __bool__(self): """True if has balance, False if balance is 0""" return self.balance > 0 # Creating objects account1 = BankAccount("Alice", 1000000) account2 = BankAccount("Bob", 500000) # Magic methods in action print(account1) # __str__ print(repr(account1)) # __repr__ print(len(account1)) # __len__ (name length) # Comparison print(account1 == account2) # __eq__ print(account1 > account2) # __lt__ (reversed) # Arithmetic operations account1 + 500000 # __add__ (deposit) print(account1) account1 - 200000 # __sub__ (withdraw) print(account1) # Boolean conversion empty_account = BankAccount("Charlie", 0) print(bool(account1)) # True print(bool(empty_account)) # False # Using in conditionals if account1: print(f"{account1.owner} has balance") else: print(f"{account1.owner} has no balance")` }]} /> ## Object-Oriented Programming Practice Let's create a more complex example to understand how OOP is applied in real scenarios. By understanding the concept that everything is an object in Python, you can write code that is more structured, easier to understand, and easier to maintain. Object-oriented programming allows you to model real-world problems into code in a natural and intuitive way.