Search notes:

Python: descriptor

A descriptor is an object that defines at least one of the dunders __get__, __set__ or __delete__.
class desc:

  def __get__(self, obj, objtype):
      print('__get__ was called, obj.ident =', obj.ident)
      return self.val

  def __set__(self, obj, val):
      print('__set__ was called, obj.ident =', obj.ident)
      self.val = val

  def __delete__(self, obj):
      print('__delete__ was called, obj.ident =', obj.ident)


class CLS:
#
# Note: D (the descriptor object) is a class
# variable, not an instance variable:
#
  D = desc()

  def __init__(self, ident):
      self.ident = ident


obj_a = CLS('A')
obj_b = CLS('B')

obj_a.D = 42
#
#  __set__ was called, obj.ident = A(

obj_b.D = 99
#
#  __set__ was called, obj.ident = B

val_a = obj_a.D
#
#  __get__ was called, obj.ident = A

val_b = obj_b.D
#
#  __get__ was called, obj.ident = B

print(val_a)
#
#  99

print(val_b)
#
#  99

del obj_a.D
#
#  __delete__ was called, obj.ident = A
Github repository about-Python, path: /objects/descriptor/demo.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...', 1758199811, '216.73.216.150', 'Mozilla/5.0 App...', NULL) #2 /home/httpd/vhosts/renenyffenegger.ch/httpsdocs/notes/development/languages/Python/objects/descriptor/index(90): insert_webrequest() #3 {main} thrown in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php on line 78