2

When I init a class in python, is it only called once? For example, if I write an if statement in the init area.

class hi():
    def __init__():
        # bla bla bla

Does it only loop over once?

2
  • 1
    __init__ is only called once for each time you instantiate the class. Having said that your question is not completely clear. if statements never loop under any conditions. Commented Sep 26, 2016 at 23:38
  • Oh. Sorry for the ambiguity of my question. Thanks anyway. Commented Sep 26, 2016 at 23:40

2 Answers 2

1

__init__ is the constructor of the class. It is called once for every instance of the class you create.

class A(object):
    def __init__(self):
        print('__init__ called')

a1 = A()  # prints: __init__ called
a2 = A()  # prints: __init__ called

BTW, this is not something specific to pygame, but python in general.

The constructor always takes at least one argument: self. It can take additional arguments. self is the instance which is being constructed and you can write initialization of it in the constructor.

class A(object):
    def __init__(self, value):
        self.value = value

a1 = A(17)

print (a1.value) # prints: 17
Sign up to request clarification or add additional context in comments.

Comments

1

The init function is ideally used to declare variables in oops style of python.

def classA:
        def __init__(self):
           self.somevariable = somevalue 

def classB:
        def __init__(self):
            #again declare some variables

If you use classB, you can use both the variables of classA as well as that of classB. However if there was no init in classB then only that of classA will be used. As for your question i would say that it can run again. I assume that by looping you mean if it can be used again.

Comments

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.