-1

I have a class that contains a number of methods:

class PersonalDetails(ManagedObjectABC):
    def __init__(self, personal_details):
        self.personal_details = personal_details
    def set_gender(self):
        self.gender='Male:
    def set_age(self):
        self.set_age=22
    etc.

I have many such methods, all that begin with the word `set. I want to create a new method within this class that will execute all methods that begin with set, like this:

def execute_all_settings(self):
    '''
    wrapper for setting all variables that start with set.
    Will skip anything not matching regex '^set'
    '''
    to_execute=[f'''self.{i}()''' for i in dir(self) if re.search('^set',i)
    print(to_execute)
    [exec(i) for i in to_execute]

However, this reports an error:

NameError: name 'self' is not defined

How can I go about doing this?

more info

The reason I want to do it this way, rather than simply call each method individually, is that new methods may be added in the future, so I want to execute all methods (that start with "set" no matter what they are)

Josh
  • 1,155
  • 4
  • 12
  • 21

1 Answers1

1

Do not use either exec or eval. Instead use getattr.

Also note that set_age is both a method and an attribute, try to avoid that.

import re

class PersonalDetails:
    def __init__(self, personal_details):
        self.personal_details = personal_details

    def set_gender(self):
        self.gender = 'Male'

    def set_age(self):
        self.age = 22

    def execute_all_settings(self):
        '''
        wrapper for setting all variables that start with set.
        Will skip anything not matching regex '^set'
        '''
        to_execute = [i for i in dir(self) if re.search('^set', i)]
        print(to_execute)
        for func_name in to_execute:
            getattr(self, func_name)()

pd = PersonalDetails('') 
pd.execute_all_settings() 
print(pd.gender)
# ['set_age', 'set_gender']
# Male

This solution will work as long as all the "set" methods either do not expect any arguments (which is the current use-case), or they all expect the same arguments.

DeepSpace
  • 78,697
  • 11
  • 109
  • 154