Last modified: Dec 01, 2026

Python Class with Arguments

Classes are the building blocks of object-oriented Python. They let you group data and behavior together.

Most real classes need input. That input comes through arguments. This guide shows how to pass arguments to a Python class.

You will learn the __init__ method, default values, keyword arguments, and common mistakes. Every section includes runnable code.

What Is a Python Class with Arguments?

A class with arguments accepts input when you create an object. The input is stored on the instance.

The __init__ method handles this. It runs automatically when you call the class.

Think of __init__ as a setup step. It prepares each new object with the values you provide.


class Dog:
    def __init__(self, name, age):
        # Store the arguments on the instance
        self.name = name
        self.age = age

# Pass arguments when creating the object
my_dog = Dog("Rex", 3)
print(my_dog.name)
print(my_dog.age)

Rex
3

Here, "Rex" and 3 are arguments. The class turns them into attributes.

Learning how attributes work is the next step. This guide on Python Class Methods and Attributes explains the details clearly.

How the __init__ Method Works

The first parameter of __init__ is always self. It refers to the object being created.

The remaining parameters are the arguments you pass in. You can name them anything.

Python passes self automatically. You never provide it yourself.


class Book:
    def __init__(self, title, author, pages):
        self.title = title
        self.author = author
        self.pages = pages

book = Book("Python Basics", "Jane Doe", 250)
print(book.title, book.author, book.pages)

Python Basics Jane Doe 250

Each argument maps to one parameter. The order matters when you use positional arguments.

You can also add methods to these objects. See practical Python Class Methods Examples to build on this foundation.

Positional Arguments

Positional arguments are passed in order. The first value goes to the first parameter, and so on.

This is simple but risky. Swapping two values of the same type can cause silent bugs.


class Point:
    def __init__(self, x, y):
        self.x = x
        self.y = y

p = Point(10, 20)
print(p.x, p.y)

# Wrong order, no error raised
q = Point(20, 10)
print(q.x, q.y)

10 20
20 10

The second object looks valid. But the values are swapped. Keyword arguments prevent this problem.

Keyword Arguments

Keyword arguments let you name each value. The order no longer matters.

This makes calls readable. It also reduces mistakes.


class User:
    def __init__(self, first_name, last_name, email):
        self.first_name = first_name
        self.last_name = last_name
        self.email = email

# Order does not matter with keyword arguments
user = User(
    email="[email protected]",
    first_name="Sam",
    last_name="Lee"
)

print(user.first_name, user.last_name, user.email)

Sam Lee [email protected]

Use keyword arguments when a class has many parameters. Your future self will thank you.

Default Arguments

You can give parameters default values. The caller can then skip them.

Defaults make classes easier to use. They also keep the API flexible.


class Account:
    def __init__(self, owner, balance=0, active=True):
        self.owner = owner
        self.balance = balance
        self.active = active

a1 = Account("Mia")
a2 = Account("Leo", 500, False)

print(a1.owner, a1.balance, a1.active)
print(a2.owner, a2.balance, a2.active)

Mia 0 True
Leo 500 False

Parameters with defaults must come after parameters without them. Python raises a SyntaxError if you break this rule.

The Mutable Default Trap

This is a classic beginner mistake. Never use a mutable object as a default value.

Lists, dictionaries, and sets are mutable. A shared default is created only once.


# Bad example: shared list default
class Team:
    def __init__(self, name, members=[]):
        self.name = name
        self.members = members

t1 = Team("Red")
t1.members.append("Alex")

t2 = Team("Blue")
print(t2.members)  # Unexpected!

['Alex']

The second team should have no members. Instead, it shares the same list.

The fix is to use None as the default. Then create a fresh object inside the method.


class Team:
    def __init__(self, name, members=None):
        self.name = name
        # Create a new list for each instance
        self.members = members if members is not None else []

t1 = Team("Red")
t1.members.append("Alex")

t2 = Team("Blue")
print(t2.members)

[]

This pattern is safe and clear. Use it whenever a default could be mutated.

Using *args and **kwargs

Sometimes you do not know how many arguments will arrive. Python offers *args and **kwargs for this.

*args collects extra positional arguments as a tuple. **kwargs collects extra keyword arguments as a dictionary.


class Config:
    def __init__(self, name, *args, **kwargs):
        self.name = name
        self.extras = args
        self.options = kwargs

c = Config("app", "debug", "verbose", port=8080, secure=True)
print(c.name)
print(c.extras)
print(c.options)

app
('debug', 'verbose')
{'port': 8080, 'secure': True}

Use these tools sparingly. They are powerful but can hide errors.

Validating Arguments

A good class checks its input. This prevents bad objects from existing.

Raise ValueError or TypeError when input is invalid.


class Rectangle:
    def __init__(self, width, height):
        if width <= 0 or height <= 0:
            raise ValueError("Width and height must be positive")
        self.width = width
        self.height = height

    def area(self):
        return self.width * self.height

r = Rectangle(4, 5)
print(r.area())

try:
    bad = Rectangle(-1, 5)
except ValueError as e:
    print(e)

20
Width and height must be positive

Validation keeps your objects consistent. It also makes debugging easier later.

Arguments and Properties

Arguments set initial values. Properties control access after creation.

You can combine both. Validate in the setter, not only in __init__.


class Temperature:
    def __init__(self, celsius):
        self.celsius = celsius  # Calls the setter below

    @property
    def celsius(self):
        return self._celsius

    @celsius.setter
    def celsius(self, value):
        if value < -273.15:
            raise ValueError("Below absolute zero")
        self._celsius = value

t = Temperature(25)
print(t.celsius)

25

This approach keeps rules in one place. To compare both concepts, read Python Property vs Attribute: Clear Guide.

Properties can also accept arguments in advanced cases. Learn more in Python Property with Arguments.

Class Arguments vs Instance Arguments

Arguments passed to __init__ belong to one instance. Each object gets its own copy.

Class attributes are shared. They are defined outside methods. Mixing the two up causes confusing bugs.


class Counter:
    count = 0  # Class attribute, shared

    def __init__(self, name):
        self.name = name  # Instance attribute

c1 = Counter("one")
c2 = Counter("two")

print(c1.name, c2.name)
print(Counter.count)

one two
0

Instance arguments are usually what you want. Shared state should be intentional.

Common Errors to Avoid

Several errors appear again and again. Knowing them saves time.

Missing arguments raise a TypeError. The message tells you which parameter is missing.


class Car:
    def __init__(self, brand, model):
        self.brand = brand
        self.model = model

# Missing one argument
car = Car("Toyota")

TypeError: Car.__init__() missing 1 required positional argument: 'model'

Extra arguments also raise a TypeError. Check your call against the method signature.

Forgetting self is another common slip. Always include it as the first parameter.

Best Practices

Keep constructors short. Do the minimum needed to create a valid object.

Use keyword arguments for classes with more than three parameters. It improves readability.

Validate input early. Raise clear errors with helpful messages.

Avoid mutable defaults. Use None and create fresh objects inside the method.

Prefer properties for computed or guarded values. They keep your API clean and safe.

Conclusion

A Python class with arguments is a core skill. The __init__ method makes it work.

You now know positional and keyword arguments. You can use defaults, validation, and *args and **kwargs.

You also know the mutable default trap and how to avoid it. These habits prevent subtle bugs.

Start with simple constructors. Add validation and properties as your classes grow. Your code will stay clean, readable, and easy to maintain.