Search notes:

Python: static class members

Static class member are possible in classes.
In order to create a static variable (aka class-variable) is created as part of the class statement by assigning a value to a variable. This variable then becomes the static data member.
In order to define a static method, the def statement needs to be prefixed with @staticmethod.
class C:

 #
 # Define a class variable (aka static member):
 #
   creation_counter = 0

   def __init__(self):

     #
     # increment
     #
       C.creation_counter += 1

     #
     # Assign a value to self.created which
     # effectively creates an instance variable:
     #
       self.created = C.creation_counter

 #
 # Define a static method. Note the «@staticmethod»
 #
   @staticmethod
   def printCreationCounter():
       print('The current value of creation_counter is {}'.format(C.creation_counter))

 #
 # Define an instance-method:
 #
   def printCreated(self):
       print('This instance has creation number {}'.format(self.created))


C.printCreationCounter()
#
#  The current value of creation_counter is 0


obj_1 = C()
obj_2 = C()

C.printCreationCounter()
#
# The current value of creation_counter is 2

obj_3 = C()


obj_3.printCreated()
#
# This instance has creation number 3

obj_1.printCreated()
#
# This instance has creation number 1

obj_2.printCreated()
#
# This instance has creation number 2
Github repository about-Python, path: /class/member/static.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...', 1759419936, '216.73.216.42', 'Mozilla/5.0 App...', NULL) #2 /home/httpd/vhosts/renenyffenegger.ch/httpsdocs/notes/development/languages/Python/class/member/static(101): insert_webrequest() #3 {main} thrown in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php on line 78