0

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.

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Eason Wang
  • 29
  • 1
  • 6

2 Answers2

2

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
2pichar
  • 1,348
  • 4
  • 17
  • Thanks a lot and I got it! But I still have and futher question about this problem (that is how and when the memebers in a class was bound to the instance) at [this page](https://stackoverflow.com/questions/72095345/how-other-members-of-a-python-class-are-bound-to-the-instance) – Eason Wang May 03 '22 at 06:07
0

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"
clemens
  • 73
  • 2
  • 7
  • Thanks a lot, I got it. But I still have and futher question about this problem (that is how and when the memebers in a class was bound to the instance) at [this page](https://stackoverflow.com/questions/72095345/how-other-members-of-a-python-class-are-bound-to-the-instance) – Eason Wang May 03 '22 at 06:04