Phil Phil - 5 months ago 8
Python Question

Self referencing variables passed during the instantiation of a class

I'm not sure if I'm using the correct terminology, but here's my code:

class Candidate(object):
def __init__(self, party_code, state, age=random.randint(35, 70),
social_index=(1 if party_code == 'dem' else -1 if party_code == 'rep' else 0),
econ_index=(-1 if party_code == 'dem' else 1 if party_code == 'rep' else 0)):
self.state = state
self.party_code = party_code
self.age = age
self.social_index = social_index
self.econ_index = econ_index


I would like to be able to use party_code to determine what the initial values of social_index and econ_index will be, but this isn't allowed with the way I currently have it set up. Is there an alternative way to dynamically set keyword variable on creation of this class?

Answer

Assuming you want social_index and econ_index to be parameters your code would look like:

class Candidate(object):
    def __init__(self, party_code, state, age=None,
            social_index=None, econ_index=None):
        if age is None:
            age=random.randint(35, 70)
        if social_index is None:
            social_index = (1 if party_code == 'dem' else -1 if party_code == 'rep' else 0)
        if econ_index is None:
            econ_index=(-1 if party_code == 'dem' else 1 if party_code == 'rep' else 0)
        self.state = state
        self.party_code = party_code
        self.age = age
        self.social_index = social_index
        self.econ_index = econ_index

You need to specify the logic to determine the values in the function body in order for it to be executed when the function is called. The default to the function is determined at definition (the def block) which is why the Mutable default trap exists.

On the other hand if you don't need to be able to pass them as arguments you can simplify it to this:

class Candidate(object):
    def __init__(self, party_code, state):
        self.state = state
        self.party_code = party_code
        self.age = random.randint(35, 70)
        if party_code == 'dem':
            self.social_index = 1
            self.econ_index = -1
        elif party_code == "rep":
            self.social_index = 0
            self.econ_index = 0
        else:
            self.social_index = 0
            self.econ_index = 0