Ahriri
Ahriri

Reputation: 29

Why is 'Class ... ' excuted only once when I created several instances?

I wrote codes as follow:

class a:
    print('hello')
    def __init__(self):
        self.name = 'Adam'
b = a()
c = a()

There is only one 'hello' involved, although I creat instances of Class a twice.

hello

It seems that codeblocks below 'class a' only be excuted one time even though I creat the instances twice. I am confused and I want to know how it works.

Upvotes: 0

Views: 38

Answers (2)

clemens
clemens

Reputation: 83

Just because you initialize a new object, you do not call the code within its class.

You just call the __init__. Method.

When Python first "reads" your code, it runs it all. And if it encounters a print() statement, it will run it too. So, the python interpreter sees your code like this:

# It runs this line - Just a comment, so nothing to run

# A class deceleration, let us look at its body and then store it
class a:
    # A print statement - I will run it. It does not add to the body, but I run all of the code I see
    print('hello')
    # This defines a method, so I will add it to the members of a
    def __init__(self):
        self.name = 'Adam'

#  A new variable, I will call `__init__` - But just `__init__`
# I will not reparse the entire block, I will just jump to the location (Assuming JIT) where that function is stored and run it
b = a()
c = a()

So, we could rewrite your entire code like this:

print("hello")
class a:
    def __init__():
         pass

b = a()
b.name = "Adam"
c = a()
c.name = "Adam"

Upvotes: 0

2pichar
2pichar

Reputation: 1378

The code inside a class is only run once, when the program is run. After that, when you instantiate that class (__init__), the code inside the __init__ method is called.

So, if you have a class like this:

class A:
    print('A run')
    def __init__(self, name):
        print(f'A init {name}')
b = A('B')
c = A('C')

What is printed is:

A run
A init B
A init C

Upvotes: 2

Related Questions