10

Consider the following code

class Foo:
    i = 1 # initialization
    def __init__(self):
        self.i += 1

t = Foo()
print(t.i)

When exactly does the initialization of i take place? Before the execution of the init method or after it?

2
  • 3
    That's a class attribute, it's defined when the class is. You can access Foo.i prior to instantiation. Commented May 4, 2019 at 14:15
  • 1
    Looking at Foo.i vs t.i may be informative: ideone.com/NPWMSX Commented May 4, 2019 at 14:29

2 Answers 2

11

Before.

The __init__ method isn't run until Foo is instantiated. i=1 is run whenever the class definition is encountered in the code

You can see this by adding print statements:

print('Before Foo')
class Foo:
    i = 1
    print(f'Foo.i is now {i}')
    
    def __init__(self):
        print('Inside __init__')
        self.i += 1
        print(f'i is now {self.i}')
print('After Foo')

print('Before __init__')
foo = Foo()
print('After __init__')

which prints:

Before Foo
Foo.i is now 1
After Foo
Before __init__
Inside __init__
i is now 2
After __init__

Notice however, that your self.i += 1 does not modify the class attribute Foo.i.

foo.i # This is 2
Foo.i # This is 1
Sign up to request clarification or add additional context in comments.

4 Comments

i = 1 would be run in the local scope, but i += 1 just raises an error
@MadPhysicist He added self, so it's not an error.
Thanks for the tip about unnamed functions (f''). Like it a lot.
@Dan That is what's commonly called f-strings. It's for string formatting. python.org/dev/peps/pep-0498
0

The class attribute is initialized the first time you use the ClassName in the source code, also you use the class attribute in the code by doing ClassMethod.attribute

class Foo:
    i = 1 # initialization
    def __init__(self):
        #Use ClassName.attribute to access class attribute
        Foo.i += 1

#I used the Name of the class here, Foo.i will be 1
print(Foo.i)
#1

#Instantiated Foo
t = Foo()

#Value of i changes to 2
print(t.i)
#2

5 Comments

Hi @chepner, thanks for the edit but should it be static class attribute instead?
No, the only thing in Python with "static" in its name is the static method.
Yes a class method or an attribute is inherently static
Define "static" in Python.
That is something I don't have an answer @chepner Could you explain or provide an example :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.