docyoda
docyoda

Reputation: 31

Add argument to function after it's already been called?

For example, if I have the function:

def to_full_name(first_name, last_name=None): # Note that 'last_name' is not required, so an error will not occur
    return '{} {}'.format(first_name, last_name)



# ...



a = to_full_name('John')

How can I add the second argument to the 'a' variable later down the line? ex:

a.set_argument('last_name', 'Doe')

Upvotes: 0

Views: 43

Answers (1)

TheLazyScripter
TheLazyScripter

Reputation: 2665

For this particular problem I would recommend a class.

class Person:
    def __init__(self, first_name=None, last_name=None):
        self.first_name = first_name
        self.last_name = last_name

    def set_first_name(self, name):
        self.first_name = name

    def set_last_name(self, name):
        self.last_name = name

    def to_full_name(): 
        return '{} {}'.format(self.first_name, self.last_name)

Then we change it as follows

person = Person("John")
person.set_last_name("Doe")
print(person.to_full_name())

We can also change the values directly

person = Person()
person.last_name = "Doe"
person.first_name = "John"
print(person.to_full_name())

Upvotes: 1

Related Questions