Search notes:

Python: getattr

getattr(obj, name) allows to refer to an attribute in an object by its name given as string:
class cls:

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

      def f1(self):
          print('f1 was called, ident = {}'.format(self.ident))

      def f2(self):
          print('f2 was called, ident = {}'.format(self.ident))


def callMethodByName(obj, name):
    method = getattr(obj, name)
    method()


obj_1 = cls('one')
obj_2 = cls('two')

callMethodByName(obj_1, 'f1') # f1 was called, ident = one
callMethodByName(obj_2, 'f2') # f2 was called, ident = two
Github repository about-Python, path: /builtin-functions/getattr/demo.py

See also

The delattr built-in function
The __getattr__ dunder.
Python: Built in functions

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...', 1758199136, '216.73.216.150', 'Mozilla/5.0 App...', NULL) #2 /home/httpd/vhosts/renenyffenegger.ch/httpsdocs/notes/development/languages/Python/built-in-functions/getattr/index(65): insert_webrequest() #3 {main} thrown in /home/httpd/vhosts/renenyffenegger.ch/php/web-request-database.php on line 78