Python classes for Java developers: __init__, self, dataclasses and Pydantic

A Python class is a Java class with less typing: __init__ is the constructor, self is this, and there's no new. Then come the two shortcuts you'll see everywhere: @dataclass, Python's record, and Pydantic, a record that validates its data.

Left, a Java sheet tagged record: record Ticket with String title and int priority, created with new Ticket Login, 2. An arrow points right to a dark Python sheet tagged validates: class Ticket extends BaseModel with title colon str and priority colon int, created with title Login and priority as the string 2, which becomes the number 2. Caption: @dataclass is the record, Pydantic adds validation.
Fig. 1 — A Java record next to a Pydantic model. Pydantic also checks and converts the data: "2" becomes 2.

You’ve written hundreds of Java classes. Python classes do the same job with less code, and a few habits change: the constructor has a strange name, this becomes an explicit parameter, and getters and setters mostly disappear.

Then there are the two shortcuts that show up in almost every modern Python project: @dataclass, which is Python’s version of a Java record, and Pydantic, a record that also checks and converts its data. If you read AI or web code in Python, you’ll see Pydantic on nearly every page.

This is part 6 of Python for Java Developers. Part 5 covered functions and keyword arguments, which every method below uses.

A class, side by side

public class Document {
    private final String id;
    private final String text;

    public Document(String id, String text) {
        this.id = id;
        this.text = text;
    }

    public int length() { return text.length(); }
}

Document doc = new Document("d1", "Hello");
class Document:
    def __init__(self, id, text):
        self.id = id
        self.text = text

    def length(self):
        return len(self.text)

doc = Document("d1", "Hello")

What changed:

  • __init__ is the constructor. Python calls it for you when you create the object.
  • self is this, but you must write it as the first parameter of every method. When you call doc.length(), Python passes doc as self.
  • Fields aren’t declared up front. Assigning self.text = ... inside __init__ creates the field.
  • No new. You call the class like a function.
  • No access modifiers. Everything is public. A leading underscore, self._cache, means “internal” by convention.

Inheritance and super()

class PdfDocument(Document):            # extends Document
    def __init__(self, id, text, pages):
        super().__init__(id, text)      # call the parent constructor
        self.pages = pages

    def length(self):                   # override: no @Override needed
        return super().length() + self.pages

class Child(Parent): is extends. Python also allows several parent classes, but in application code you’ll rarely need it. For interface-like contracts, Python uses abstract base classes (abc.ABC) or, more often, nothing at all: if an object has the right methods, it works. That’s called duck typing.

Dunder methods: toString, equals and friends

Methods with double underscores on both sides, pronounced “dunder”, are hooks that Python calls for you:

Python Java Called by
__init__ constructor Document(...)
__repr__ toString() print(obj), the REPL, logs
__str__ toString() for users str(obj), print(obj)
__eq__ equals() a == b
__hash__ hashCode() dict keys, sets
__len__ size() len(obj)
__lt__ compareTo() a < b, sorted()
class Document:
    ...
    def __repr__(self):
        return f"Document({self.id!r}, {len(self.text)} chars)"

Without __eq__, == falls back to identity, like Java’s default equals.

@property instead of getters and setters

Python code accesses fields directly: doc.text, not doc.getText(). If you later need logic behind a field, you turn it into a property without changing any caller:

class Document:
    def __init__(self, text):
        self.text = text

    @property
    def word_count(self):          # read like a field: doc.word_count
        return len(self.text.split())

So don’t write get_text() methods “just in case”. Start with plain attributes and add @property when you need it.

Static and class methods

class Ticket:
    def __init__(self, title, priority):
        self.title = title
        self.priority = priority

    @staticmethod
    def is_valid_priority(p):            # Java: static method
        return 1 <= p <= 5

    @classmethod
    def from_dict(cls, data):            # an alternative constructor
        return cls(data["title"], data["priority"])

t = Ticket.from_dict({"title": "Login fails", "priority": 2})

@classmethod receives the class itself as cls. It’s the Pythonic way to write a static factory like Ticket.of(...), and it works correctly for subclasses.

@dataclass: Python’s record

Writing __init__, __repr__ and __eq__ by hand for every data class gets old, just as it did in Java before records. A dataclass writes them for you:

record Chunk(String docId, String text, double score) {}

var c = new Chunk("d1", "Some text", 0.0);
from dataclasses import dataclass

@dataclass(frozen=True)
class Chunk:
    doc_id: str
    text: str
    score: float = 0.0

c = Chunk("d1", "Some text")
print(c)   # Chunk(doc_id='d1', text='Some text', score=0.0)

The name: type lines declare the fields. @dataclass generates __init__, __repr__ and __eq__ from them; frozen=True makes the object immutable like a record (and hashable). Without frozen, the fields can be changed.

For a list or dict field, use field(default_factory=list) instead of = [], for the same reason as the mutable default trap:

from dataclasses import dataclass, field

@dataclass
class Conversation:
    user_id: str
    messages: list[dict] = field(default_factory=list)

If you know Java records, you already know when to use a dataclass: for plain data that two objects with the same values should treat as equal.

Pydantic: the class you’ll see most in AI code

Pydantic is a third-party library (pip install pydantic), but it’s so common it feels built in. A Pydantic model looks like a dataclass, except that it checks and converts data when the object is created:

from pydantic import BaseModel, ValidationError

class Ticket(BaseModel):
    title: str
    priority: int
    tags: list[str] = []

t = Ticket(title="Login fails", priority="2")   # "2" is converted to 2
t.priority                                      # 2

try:
    Ticket(title="Login fails", priority="high")
except ValidationError as e:
    print(e)        # explains that priority must be an integer

That matters when data comes from outside your code: a JSON request body, a config file, or the output of an LLM. The three methods to know:

Ticket.model_validate({"title": "x", "priority": 1})          # from a dict
Ticket.model_validate_json('{"title": "x", "priority": 1}')   # from JSON text
t.model_dump()                                                # back to a dict
t.model_dump_json()                                           # back to JSON text

For a Java developer, think of Pydantic as a record plus Jackson plus Bean Validation, in one small class. You can add constraints too: priority: int = Field(ge=1, le=5) works like @Min(1) @Max(5). (In Pydantic, a [] default is safe: it copies it for each object.)

FastAPI uses Pydantic models for request and response bodies, and LLM libraries use them to describe and check structured output.

Which one should I use?

You need Use Java cousin
Behaviour and state together (a client, a service) A plain class A normal class
Plain data inside your code @dataclass record
Data from outside (JSON, API, LLM output) Pydantic BaseModel record + Jackson + Bean Validation

Traps for Java developers

  • Forgetting self. def length(): inside a class fails with a confusing error about the number of arguments. Every method’s first parameter is self.
  • Fields declared at class level. class A: items = [] creates one list shared by all objects, like a static field. Instance fields belong in __init__ as self.items = [].
  • Writing getters and setters. Use plain attributes, and @property when you need logic.
  • Mutable defaults in dataclasses. Use field(default_factory=list); Python raises an error if you write = [].

Key takeaways

  • __init__ is the constructor, self is this (written explicitly), and there’s no new.
  • class Child(Parent): is extends; call the parent with super().__init__(...).
  • Dunder methods (__repr__, __eq__, __len__) are Python’s toString, equals and size.
  • Use plain attributes and @property instead of getters and setters.
  • @dataclass(frozen=True) is Python’s record.
  • Pydantic BaseModel adds validation and JSON conversion; use it for data from outside your code.

Frequently asked questions

What is init in Python?

It’s the method Python calls to set up a new object, the equivalent of a Java constructor. Its first parameter is self, the object being created, and it assigns the fields with self.name = value.

What is self in Python?

self is the object a method was called on, the same thing as this in Java. The difference is that Python makes it an explicit first parameter in every method definition.

Does Python have records like Java?

The closest thing is a dataclass: @dataclass(frozen=True) generates the constructor, __repr__ and __eq__, and makes the object immutable. typing.NamedTuple is another option for small, tuple-like records.

What is Pydantic in Python?

A library for data classes that validate and convert their data. You declare fields with type hints, and Pydantic checks incoming values, converts compatible ones (like "2" to 2), and raises a clear error for the rest. It’s used heavily by FastAPI and AI libraries.

Does Python have private fields?

Not enforced ones. A leading underscore (self._cache) marks a field as internal by convention. A double underscore (self.__cache) triggers name mangling, which makes accidental access harder, but it’s rarely needed.

Next in the series: Python exceptions for Java developers: try, except, raise, and life without checked exceptions.

Comments

LEAVE A COMMENT
No sign-up. Comments appear after a quick review.