在函数被调用后添加参数?

时间:2019-10-19 01:13:06

标签: python python-3.x function arguments

例如,如果我具有以下功能:

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')

如何在第二行后面将第二个参数添加到'a'变量中?例如:

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

1 个答案:

答案 0 :(得分:1)

对于这个特殊的问题,我建议上一堂课。

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)

然后我们将其更改如下

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

我们也可以直接更改值

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