Extending bp's answer, I wanted to show you what he meant by immutable types.

First, this is okay:

>>> class TestB():
...     def __init__(self, attr=1):
...         self.attr = attr
...     
>>> a = TestB()
>>> b = TestB()
>>> a.attr = 2
>>> a.attr
2
>>> b.attr
1

However, this only works for immutable (unchangable) types. If the default value was mutable (meaning it can be replaced), this would happen instead:

>>> class Test():
...     def __init__(self, attr=[]):
...         self.attr = attr
...     
>>> a = Test()
>>> b = Test()
>>> a.attr.append(1)
>>> a.attr
[1]
>>> b.attr
[1]
>>> 

Note that both a and b have a shared attribute. This is often unwanted.

This is the Pythonic way of defining default values for instance variables, when the type is mutable:

>>> class TestC():
...     def __init__(self, attr=None):
...         if attr is None:
...             attr = []
...         self.attr = attr
...     
>>> a = TestC()
>>> b = TestC()
>>> a.attr.append(1)
>>> a.attr
[1]
>>> b.attr
[]

The reason my first snippet of code works is because, with immutable types, Python creates a new instance of it whenever you want one. If you needed to add 1 to 1, Python makes a new 2 for you, because the old 1 cannot be changed. The reason is mostly for hashing, I believe.

Answer from Xavier Ho on Stack Overflow
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ python_class_init.asp
Python __init__() Method
With __init__(), you can set initial values when creating the object: class Person: def __init__(self, name, age): self.name = name self.age = age p1 = Person("Linus", 28) print(p1.name) print(p1.age) Try it Yourself ยป ยท You can also set default values for parameters in the __init__() method:
๐ŸŒ
Rip Tutorial
riptutorial.com โ€บ default values for instance variables
Python Language Tutorial => Default values for instance variables
Similarities in syntax, Differences in meaning: Python vs. JavaScript ... If the variable contains a value of an immutable type (e.g. a string) then it is okay to assign a default value like this ยท class Rectangle(object): def __init__(self, width, height, color='blue'): self.width = width self.height = height self.color = color def area(self): return self.width * self.height # Create some instances of the class default_rectangle = Rectangle(2, 3) print(default_rectangle.color) # blue red_rectangle = Rectangle(2, 3, 'red') print(red_rectangle.color) # red
Discussions

class - How should I declare default values for instance variables in Python? - Stack Overflow
Should I give my class members default values like this: class Foo: num = 1 or like this? class Foo: def __init__(self): self.num = 1 In this question I discovered that in both ca... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Python: Are these default values being passed to the __init__ function necessary? - Stack Overflow
Here is a screenshot from a lecture that I am going through at school: My question is, if the class data fields are already being defined: slices=16 temperature=75.0 Do those values (16 and 75.0)... More on stackoverflow.com
๐ŸŒ stackoverflow.com
class init method: best way for default value assignments
The second allows you to override the default value of next if you want. In the first example, next will always be initialized to None. It's a design decision. class MyClass1: def __init__(self, x=None): self.x = x class MyClass2: def __init__(self): self.x = None c1 = MyClass1(5) print(c1.x) # prints 5 c2 = MyClass1() print(c2.x) # prints None c3 = MyClass2() print(c3.x) # prints None More on reddit.com
๐ŸŒ r/learnpython
3
1
December 18, 2021
python - How to assign "default" values in class? - Stack Overflow
Communities for your favorite technologies. Explore all Collectives ยท Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
๐ŸŒ stackoverflow.com
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ default values in class definition and constructor? is this the right way?
r/learnpython on Reddit: Default values in class definition and constructor? Is this the right way?
August 15, 2015 -

I'm wondering if this is the right way to do this. It seems... odd somehow to assign default values in the class definition, then default None in the constructor. I suppose I could give the same default values in both places, but again, this feels like unnecessarily repeating myself.

class MyClass:
    name = 'Undefined'
    number = -1

    def __init__(self, name=None, number=None):
        if name is not None:
            self.name = name
        if number is not None:
            self.number = number
๐ŸŒ
Python Examples
pythonexamples.org โ€บ python-default-values-for-properties-in-class
Set Default Values for Properties in Class in Python
class Person: name="NA" age="0" ... Person Details Name : Mike Age : 21 ยท As we already mentioned, we can use named parameters in __init__() function definition to set default value for the properties....
Top answer
1 of 6
187

Extending bp's answer, I wanted to show you what he meant by immutable types.

First, this is okay:

>>> class TestB():
...     def __init__(self, attr=1):
...         self.attr = attr
...     
>>> a = TestB()
>>> b = TestB()
>>> a.attr = 2
>>> a.attr
2
>>> b.attr
1

However, this only works for immutable (unchangable) types. If the default value was mutable (meaning it can be replaced), this would happen instead:

>>> class Test():
...     def __init__(self, attr=[]):
...         self.attr = attr
...     
>>> a = Test()
>>> b = Test()
>>> a.attr.append(1)
>>> a.attr
[1]
>>> b.attr
[1]
>>> 

Note that both a and b have a shared attribute. This is often unwanted.

This is the Pythonic way of defining default values for instance variables, when the type is mutable:

>>> class TestC():
...     def __init__(self, attr=None):
...         if attr is None:
...             attr = []
...         self.attr = attr
...     
>>> a = TestC()
>>> b = TestC()
>>> a.attr.append(1)
>>> a.attr
[1]
>>> b.attr
[]

The reason my first snippet of code works is because, with immutable types, Python creates a new instance of it whenever you want one. If you needed to add 1 to 1, Python makes a new 2 for you, because the old 1 cannot be changed. The reason is mostly for hashing, I believe.

2 of 6
83

The two snippets do different things, so it's not a matter of taste but a matter of what's the right behaviour in your context. Python documentation explains the difference, but here are some examples:

Exhibit A

class Foo:
  def __init__(self):
    self.num = 1

This binds num to the Foo instances. Change to this field is not propagated to other instances.

Thus:

>>> foo1 = Foo()
>>> foo2 = Foo()
>>> foo1.num = 2
>>> foo2.num
1

Exhibit B

class Bar:
  num = 1

This binds num to the Bar class. Changes are propagated!

>>> bar1 = Bar()
>>> bar2 = Bar()
>>> bar1.num = 2 #this creates an INSTANCE variable that HIDES the propagation
>>> bar2.num
1
>>> Bar.num = 3
>>> bar2.num
3
>>> bar1.num
2
>>> bar1.__class__.num
3

Actual answer

If I do not require a class variable, but only need to set a default value for my instance variables, are both methods equally good? Or one of them more 'pythonic' than the other?

The code in exhibit B is plain wrong for this: why would you want to bind a class attribute (default value on instance creation) to the single instance?

The code in exhibit A is okay.

If you want to give defaults for instance variables in your constructor I would however do this:

class Foo:
  def __init__(self, num = None):
    self.num = num if num is not None else 1

...or even:

class Foo:
  DEFAULT_NUM = 1
  def __init__(self, num = None):
    self.num = num if num is not None else DEFAULT_NUM

...or even: (preferrable, but if and only if you are dealing with immutable types!)

class Foo:
  def __init__(self, num = 1):
    self.num = num

This way you can do:

foo1 = Foo(4)
foo2 = Foo() #use default
๐ŸŒ
W3Schools
w3schools.com โ€บ python โ€บ gloss_python_class_init.asp
Python __init__() Function
Create a class named Person, use the __init__() method to assign values for name and age: class Person: def __init__(self, name, age): self.name = name self.age = age p1 = Person("John", 36) print(p1.name) print(p1.age) Try it Yourself ยป ยท Note: The __init__() method is called automatically every time the class is being used to create a new object. Python Syntax Tutorial Class Create Class Object Methods self Modify Object Properties Delete Object Properties Delete Object Class pass Statement
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ __init__-in-python
__init__ in Python - GeeksforGeeks
... class Dog: def __init__(self, ... b.breed, b.age) ... When creating Dog("Buddy"), Python uses the defaults, breed = "Mixed", age = 1....
Published: May 11, 2026
Find elsewhere
๐ŸŒ
pythontutorials
pythontutorials.net โ€บ blog โ€บ how-should-i-declare-default-values-for-instance-variables-in-python
How to Declare Default Values for Instance Variables in Python: Class vs __init__ โ€“ Which is More Pythonic?
Python offers two primary ways to declare default values for instance variables: Class-level declaration: Assigning the default directly in the class body (outside the __init__ method).
๐ŸŒ
Thefreecoursesite
thefreecoursesite.com โ€บ python-class-init-default-arguments
Python Class Init Default Arguments
This must be done very carefully. The reason is the default values of the arguments are evaluated only once when the control reaches the function. Definition for the first time. After that, the same values(or mutable objects) are referenced in the subsequent function calls.
๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 71934568 โ€บ python-are-these-default-values-being-passed-to-the-init-function-necessary
Python: Are these default values being passed to the __init__ function necessary? - Stack Overflow
This is the example for encapsulation, and I find it so confusing why you would need both the class private variables and the self.__variables in init #!/usr/bin/python class ProtectedPizza(object): __slices=16 __temperature=75.0 def __init__(self, slices=16, temperature=75.0): self.__slices = slices self.__temperature = temperature def hasSlices(self): if self.__slices > 0: return True else: return False def getSlices(self): return self.__slices def setSlices(self, newVal): if type(newVal) is int: self.__slices = newVal; 2022-04-21T03:45:24.363Z+00:00
๐ŸŒ
Abdul Wahab Junaid
awjunaid.com โ€บ home โ€บ default values for instance variables in python
Default values for instance variables in python | Abdul Wahab Junaid
August 14, 2023 - class Person: def __init__(self, ... class has an __init__ method that takes name and age as arguments, with age having a default value of 18....
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ class init method: best way for default value assignments
r/learnpython on Reddit: class init method: best way for default value assignments
December 18, 2021 -

I am learning linked lists in python using classes.

One place that I am learning from is doing:

class Node:
    def __init__(self, value):
        self.value = value
        self.next = None

The other place is doing:

class Node:
    def __init__(self, value, next = None):
        self.value = value
        self.next = next

I can't figure out what difference it makes to use either init method. I tried to search this answer out using StackOverflow, but I had no luck.

I get that one is able to define 'next' during instantiation and the other would need to be defined after instantiation, but when would and why would you use one over the other?

edit: Thanks all. I am just starting to understand classes and still overthinking a little.

๐ŸŒ
Stack Overflow
stackoverflow.com โ€บ questions โ€บ 74737652 โ€บ how-to-assign-default-values-in-class
python - How to assign "default" values in class? - Stack Overflow
Select a class: W for warrior, M for Magician, B for Bowmaster') match x.lower: case 'w': self.playClass = 'Warrior' case 'm': self.playClass = 'Magician' case 'b': self.playClass = 'Bowmaster' def player_add_item(self, item): self.items.append(item) def player_add_level(self): self.level += 1 def player_get_class(self): return self.playClass p = player() print(p.playClass) ... Yep, thank you. New to python, have to get used to it :) ... Since you're using type annotations, you can use mypy and it ought to be able to catch errors like that for you (e.g. it'll tell you that you're trying to match a function against strings, which will never work). ... You need to assign to them in __init__; as written, they're all class attributes (shared between all instances, and visible on the class itself), not instance attributes (unique to each instance).
๐ŸŒ
Courses-for-you
courses-for-you.com โ€บ courses โ€บ python-class-init-default-values
Python Class Init Default Values
2 days ago You can use inspect.signature to obtain the parameters of the __init__ method of each "base" class โ€ฆ ... 1 day ago Web In python 2, the attribute will be func.func_defaults. As other posters have pointed out, you probably want to use None as a sentinel value and give each instance it's own list.
๐ŸŒ
Udacity
udacity.com โ€บ blog โ€บ 2021 โ€บ 11 โ€บ __init__-in-python-an-overview.html
__init__ in Python: An Overview | Udacity
June 10, 2026 - Each one would hold different values. They all came from the same class. This is the pattern you will use most often. Required parameters make it clear what data each object needs to work properly. Pythonโ€™s __init__ supports default parameter values, just like any other function.
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ dataclasses.html
dataclasses โ€” Data Classes
If a field is excluded from __init__() (using init=False) and the field also specifies default_factory, then the default factory function will always be called from the generated __init__() function. This happens because there is no other way to give the field an initial value. Python stores default member variable values in class attributes.
๐ŸŒ
LabEx
labex.io โ€บ tutorials โ€บ python-how-to-initialize-data-in-a-python-class-417302
How to initialize data in a Python class | LabEx
In this example, the __init__() method takes two parameters, name and age, and assigns them to the corresponding attributes of the Person class. You can also define class attributes directly within the class definition, outside of any methods. These attributes are shared among all instances of the class and are often used to store default or constant values.