Search notes:

Python: class statement contains other statements

The class statement is just a »container« for other statements of which the def statement is special because it creates the class's methods.
The following example tries to demonstrate how the statements within a class are executed while the class is parsed:
#!/usr/bin/python3

def globalFunc():
    print("globalFunc was called")
    return 'eggs'

print("next is definition of class TQ84")

class TQ84():

 # 
 #  The following two statements (print and calling globalFunc)
 #  are executed while this class definition is read by the
 #  parser (and not, as one might think) when the class
 #  is instantiaed.
 # 
    print("Within TQ84")
    x = globalFunc()

    def __init__(self, name):
     #
     #  However, these two statements are
     #  only executed when an instance of
     #  the class is created (but the def
     #  is executed)
     #
        print("TQ84.__init__ was called")
        self.name = name

 #
 #  Again, this print statement is executed
 #  during parsing of the class.
 #
    print("This line is after def __init__")

print("going to instantiate an instance")
foo = TQ84('foo')

print("going to instantiate another instance")
bar = TQ84('bar')
#
# next is definition of class TQ84
# Within TQ84
# globalFunc was called
# This line is after def __init__
# going to instantiate an instance
# TQ84.__init__ was called
# going to instantiate another instance
# TQ84.__init__ was called
Github repository about-python, path: /statements/class/statements.py

Index

Fatal error: Uncaught PDOException: SQLSTATE[HY000]: General error: 8 attempt to write a readonly database in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php:78 Stack trace: #0 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(78): PDOStatement->execute(Array) #1 /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php(30): insert_webrequest_('/notes/developm...', 1759606068, '216.73.216.149', 'Mozilla/5.0 App...', NULL) #2 /home/httpd/vhosts/renenyffenegger.ch/httpsdocs/notes/development/languages/Python/statements/class/statements(84): insert_webrequest() #3 {main} thrown in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php on line 78