Python Forum
Class Instances called in the wrong order
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Class Instances called in the wrong order
#1
Hi,

I started playing around with classes and defined two classes A and B. The first one with a __init__(self) method and the second one without. Just to figure out what happens in __init__

class A:

    def __init__(self):
        print("this is a test")


class B:

    print("this is a second test")


a1 = A()
b1 = B()


The output is the following:
this is a second test
this is a test
Now why exactly does python call the second instance first even though the first instance is first in the code?
Pretty sure this question popped up before but I didn't know how to search for it.

Regards
Ian
Reply
#2
Your major problem is that they aren't really classes.

The _init_ says what the instance will be like the moment it is made. Neither of those have anything about them. They don't make a thing. They are just print statements. Classes are blueprints for making objects.

Now that you have them, you have no way to tell them what to do, because they can't do anything.

Here is a super helpful video you will like:
https://www.youtube.com/watch?v=ZDa-Z5JzLYM&t=1s
Reply
#3
The answer to the question, though, is that the call to print in B is run when the class is defined (i.e. when the interpreter reads the block under class B:), while the call to print in A is only run when that class' __init__ is called.
Reply
#4
(Mar-06-2020, 04:47 AM)michael1789 Wrote: Your major problem is that they aren't really classes
That statement is not true. This is valid code and they are classes all right. But I will come to that after I answer OP question.

The print function in class B get executed once and only once - at the time of class definition and only then, i.e. it will never be executed again. You are wrong in your assumption that class B print is executed at the time of instance creation (i.e. second).
The print function in class A __init__() method is executed every time when you create new instance of class A.
Now, I doubt you will ever see print function like the one in class B in real code. However you may see class attributes instead. Look at following example:

class Foo:
    spam = 'This is class attribute spam' # this is class attribute shared between all class instances
    eggs = [] # mutable class attribute
    def __init__(self, message):
        self.message = message # this is instance attribute

    def do_something(self):
        print('\nDoing something...')
        Foo.spam = 'I did something'
        Foo.eggs.append(self.message)


print(Foo.spam) # access the class attribute
foo = Foo('This is instance foo') # create instance foo
bar = Foo('This is instance bar') # create instance bar

print('\nAccess instance foo attributes after instantiation')
print(foo.spam)
print(foo.eggs)
print(foo.message)

print('\nAccess instance bar attributes after instantiation')
print(bar.spam)
print(bar.eggs)
print(bar.message)

# change class attribute and instance attribute
Foo.spam = 'New class spam'
foo.message = 'New foo message'

print('\nAccess instance foo attributes after change')
print(foo.spam)
print(foo.eggs)
print(foo.message)

print('\nAccess instance bar attributes after change')
print(bar.spam)
print(bar.eggs)
print(bar.message)

foo.do_something()

print('\nAccess instance foo attributes after call do_something()')
print(foo.spam)
print(foo.eggs)
print(foo.message)

print('\nAccess instance bar attributes after call do_something()')
print(bar.spam)
print(bar.eggs)
print(bar.message)
Output:
This is class attribute spam Access instance foo attributes after instantiation This is class attribute spam [] This is instance foo Access instance bar attributes after instantiation This is class attribute spam [] This is instance bar Access instance foo attributes after change New class spam [] New foo message Access instance bar attributes after change New class spam [] This is instance bar Doing something... Access instance foo attributes after call do_something() I did something ['New foo message'] New foo message Access instance bar attributes after call do_something() I did something ['New foo message'] This is instance bar
@michael1789, if the class is "doing" something does not qualify it as class or not. You can see code like this

class Foo:
    pass
It may be because it's just a placeholder for a class that will be implemented later. Even before being implemented you can see other class inherit from it.
Another common use case is to define custom exceptions, e.g.
class MyError(Exception):
    pass

def make_error():
    raise MyError('This is custom error')

make_error()
Output:
Traceback (most recent call last): File "/home/buran/sandbox/pyforum.py", line 50, in <module> make_error() File "/home/buran/sandbox/pyforum.py", line 48, in make_error raise MyError('This is custom error') __main__.MyError: This is custom error
If you can't explain it to a six year old, you don't understand it yourself, Albert Einstein
How to Ask Questions The Smart Way: link and another link
Create MCV example
Debug small programs

Reply
#5
What a great explanation. Thank you so much!
You guys rock!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  super() and order of running method in class inheritance akbarza 7 595 Feb-04-2024, 09:35 AM
Last Post: Gribouillis
  Multiple variable inputs when only one is called for ChrisDall 2 449 Oct-20-2023, 07:43 PM
Last Post: deanhystad
Question [solved] Classes, assign an attributes to a class not to instances.. SpongeB0B 4 891 May-20-2023, 04:08 PM
Last Post: SpongeB0B
  Couldn't install a go-game called dlgo Nomamesse 14 2,979 Jan-05-2023, 06:38 PM
Last Post: Nomamesse
  Am I wrong or is Udemy wrong? String Slicing! Mavoz 3 2,388 Nov-05-2022, 11:33 AM
Last Post: Mavoz
  how can a function find the name by which it is called? Skaperen 18 3,322 Aug-24-2022, 04:52 PM
Last Post: Skaperen
  function with 'self' input parameter errors out with and without 'self' called dford 12 3,009 Jan-15-2022, 06:07 PM
Last Post: deanhystad
  matplotlib x-axis wrong order SchroedingersLion 4 4,181 Feb-23-2021, 05:42 PM
Last Post: nilamo
  What is this formatting called? Mark17 2 1,732 Dec-14-2020, 08:42 PM
Last Post: snippsat
  How to create a varying qty of instances of a Class and name them? KM007 2 2,011 May-29-2020, 12:30 PM
Last Post: KM007

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020