class Engine: def start(self): return "Engine started"class Wheels: def rotate(self): return "Wheels rotating"
class Car: def init(self): self.engine = Engine() self.wheels = Wheels()
def drive(self): return f"self.engine.start(), self.wheels.rotate()"
This is the most important "hidden" feature in Python OOP. Descriptors are objects that define how attribute access (get, set, delete) is handled. They are the mechanism behind property, classmethod, and even normal functions (methods).
An object is a descriptor if it defines any of: __get__, __set__, or __delete__.
Before writing complex code, you must understand how Python constructs classes and manages memory. python 3 deep dive part 4 oop
In Python 3, a class is a template that defines the properties and behavior of an object. A class is essentially a blueprint or a template that defines the characteristics of an object. An object, on the other hand, is an instance of a class, which has its own set of attributes and methods.
Here's an example of a simple class in Python 3:
class Car:
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
def honk(self):
print("Honk honk!")
In this example, Car is a class that has three attributes: make, model, and year. The __init__ method is a special method that is called when an object is created from the class. It initializes the attributes of the class. class Engine: def start(self): return "Engine started" class
The honk method is an example of a method that can be called on an object of the Car class.
class Bad: def __init__(self, items=[]): self.items = items # Shared across all instances!
class Good: def init(self, items=None): self.items = items or []
Convention: "Internal use only." It signals to other programmers that this attribute or method should not be accessed directly or overridden. It is, however, fully accessible.