Publicado · en mejora
Guía de Python · 3/6
Por ahora, este capítulo solo está disponible en inglés.
Python ships with a small set of core types and four built-in collections that cover most day-to-day data handling. This chapter shows when to reach for each one, how to define your own types with classes and dataclasses, and how type hints make intent explicit without changing how code runs.
| Type | Examples | Notes |
|---|---|---|
int | 42, 1_000_000 | Integers of unlimited size |
float | 3.14, 1e-3 | Double-precision floating point |
str | "hello", 'text' | Immutable Unicode text |
bool | True, False | Booleans |
None | None | The single value meaning "nothing here" |
7 / 2 # 3.5 (true division always gives a float)
7 // 2 # 3 (floor division)
7 % 2 # 1 (remainder)
2 ** 100 # big integers are exact, no overflow
text = "Python"
text[0] # 'P'
text[-1] # 'n'
text[1:4] # 'yth' (slicing)
"py" in text.lower() # True
value = None
if value is None: # compare with None using is, not ==
print("no value")Empty strings, zero, empty collections and None are all falsy. That is why if items: reads naturally as "if the list has anything in it".
The four built-in collections each have a clear job:
list: an ordered, mutable sequence. The workhorse.tuple: ordered but immutable. Good for fixed groupings such as coordinates or multiple return values.dict: a mapping from keys to values. It remembers insertion order.set: an unordered collection of unique values, with fast membership tests and set algebra.nums = [3, 1, 2]
nums.append(4)
nums.sort() # [1, 2, 3, 4]
point = (10, 20)
x, y = point # tuple unpacking
ages = {"mina": 31, "joon": 28}
ages["sara"] = 25
ages.get("tom", 0) # 0 when the key is missing
for name, age in ages.items():
print(name, age)
tags = {"python", "web", "python"}
tags # {'python', 'web'}
tags & {"web", "api"} # {'web'} (intersection)Lists and dicts are mutable, and assignment never copies. Two names can refer to the same list, so a change through one is visible through the other. Make an explicit copy with or when you need independence.
nums.copy()dict(ages)Define a class with class. The __init__ method initializes new instances, and every method receives the instance itself as its first parameter, conventionally named self.
class Account:
def __init__(self, owner: str, balance: int = 0) -> None:
self.owner = owner
self.balance = balance
def deposit(self, amount: int) -> None:
if amount <= 0:
raise ValueError("amount must be positive")
self.balance += amount
def __repr__(self) -> str:
return f"Account({self.owner!r}, {self.balance})"
acc = Account("mina")
acc.deposit(100)
print(acc) # Account('mina', 100)When a class mostly exists to hold data, the standard dataclasses module removes the boilerplate. List the fields with type hints and you get __init__, __repr__ and __eq__ generated for you. Pass frozen=True to make instances immutable.
from dataclasses import dataclass, field
@dataclass
class Order:
id: int
customer: str
items: list[str] = field(default_factory=list)
paid: bool = False
@dataclass(frozen=True)
class Point:
x: float
y: float
order = Order(1, "mina")
order.items.append("book")
print(order) # Order(id=1, customer='mina', items=['book'], paid=False)
Point(1, 2) == Point(1, 2) # TruePython is dynamically typed, but you can annotate variables, parameters and return values. The interpreter does not enforce these hints at runtime; instead editors use them for completion, and static checkers such as mypy and Pyright use them to catch mistakes before the code ever runs. The payoff grows with the size of the codebase.
from typing import Optional
def find_user(users: dict[str, int], name: str) -> int | None:
return users.get(name)
def average(values: list[float]) -> float:
return sum(values) / len(values) if values else 0.0
scores: list[int] = [90, 85]
lookup: dict[str, tuple[int, int]] = {"origin": (0, 0)}
maybe: Optional[str] = None # same as str | Nonepython -m pip install mypy
mypy app.pyint, float, str, bool and None; test for None with is.list for changing sequences, tuple for fixed groups, dict for lookups and set for uniqueness.@dataclass for plain data containers.
0 comentarios
Iniciar sesión · Inicia sesión para dejar un comentario.
Sé el primero en comentar.