Python classes bundle data and behavior so you can model real objects cleanly. Class definitions use the class keyword and typically include an initializer and one or more methods. Below are two practical ways to create classes, starting with the standard approach and followed by a concise data-focused option.
Method 1: Define a standard class
class Dog:
pass # temporary placeholder
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
buddy = Dog("Buddy", 3)
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def bark(self):
return f"{self.name} says woof!"
print(buddy.bark()) # Buddy says woof!
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age
def __str__(self):
return f"{self.name} ({self.age} years)"
class Dog:
species = "Canis familiaris" # class attribute shared by all dogs
def __init__(self, name, age):
self.name = name # instance attribute
self.age = age
buddy.age = 4
print(buddy.age) # 4
Use a property when an attribute needs checks or transformation without changing your public API. The built-in decorator is documented in the documentation.
class Dog:
def __init__(self, name, age):
self.name = name
self.age = age # routed via the property setter below if preferred
@property
def age(self):
return self._age
@age.setter
def age(self, value):
if not isinstance(value, (int, float)) or value < 0:
raise ValueError("age must be a non-negative number")
self._age = value
Join readers who trust AllThings.How
Add us as a preferred source on Google so our practical guides show up first next time you search.
Add to Google Preferences →Method 2: Use @dataclass for concise data containers
When a class mainly stores data, @dataclass cuts boilerplate by auto‑generating __init__, __repr__, equality, and more. Options are detailed in the documentation.
from dataclasses import dataclass
@dataclass
class Dog:
name: str
age: int
buddy = Dog("Buddy", 3)
print(buddy) # Dog(name='Buddy', age=3)
print(buddy == Dog("Buddy", 3)) # True
from dataclasses import dataclass
@dataclass
class Dog:
name: str
age: int = 0 # default value
species: str = "Canis familiaris"
def bark(self) -> str:
return f"{self.name} says woof!"
Key tips
- Use instance attributes for per-object state and class attributes for shared constants.
- Put all required fields in
__init__(or data class fields) to keep objects valid from creation. - Prefer properties to add validation later without changing attribute access syntax.
- Give objects a clear string form with
__str__for users and__repr__for developers.
That’s all you need to create practical Python classes—start with the standard pattern for behavior, or choose data classes when you mainly store fields and want less boilerplate.






