Все знают, что в Python символ звёздочки используется как оператор умножения:
product = 4 * 2 # 8
Однако, звёздочка имеет особое значение для сложных структур данных, например списков или словарей.
def add(number_1, number_2):
return number_1 + number_2
print(add(1, 2)) # 3
def add(*numbers):
sum_ = 0
for number in numbers:
sum_ += number
return sum_
print(add(1, 2, 3, 4)) # 10
def add(number_1, number_2, number_3):
return number_1 + number_2 + number_3
my_list = [1, 2, 3]
add(my_list[0], my_list[1], my_list[2])
my_list = [1, 2, 3]
print(add(*my_list)) # 6
def change_user_details(username, email, phone, date_of_birth, street_address):
user = get_user(username)
user.email = email
user.phone = phone
user.date_of_birth = date_of_birth
user.street_address = street_address
change_user_details('Олег',
email='myemail@ya.ru',
phone='+77777777777',
date_of_birth='30.08.1991',
street_address='Какая-то улица')
def change_user_details(username, **kwargs):
user = get_user(username)
user.email = kwargs['email']
user.phone = kwargs['phone']
user.date_of_birth = kwargs['date_of_birth']
user.street_address = kwargs['street_address']
def change_user_details(username, **kwargs):
user = get_user(username)
for attribute, value in kwargs.items():
setattr(user, attribute, value)
details = {
'email': 'myemail@ya.ru',
'phone': '+77777777777',
'date_of_birth': '30.08.1991',
'street_address': 'Какая-то улица'
}
change_user_detail('Олег', **details)
def my_function(*, keyword_arg_1):
pass
TypeError: my_function() takes 0 positional arguments but 1 was given
def only_positional_arguments(arg1, arg2, /):
pass
TypeError: only_positional_arguments() got some positional-only arguments passed as keyword arguments: 'arg1, arg2'
my_list_1 = [1, 2, 3]
my_list_2 = [10, 20, 30]
merged_list = my_list_1 + my_list_2
some_value = 42
merged_list = [*my_list_1, some_value, *my_list_2]
print(merged_list)
# [1, 2, 3, 42, 10, 20, 30]
social_media_details = {
'telegram': 'pythontalk_ru'
}
contact_details = {
'email': 'myemail@ya.ru'
}
user_dict = {'username': 'pythontalk', **social_media_details, **contact_details}
# {'username': 'pythontalk', 'telegram': 'pythontalk_ru', 'email': 'myemail@ya.ru'}
my_list = [1, 2, 3]
a, b, c = my_list
print(a, b, c) # 1 2 3
my_list = [1, 2, 3]
a, *b, c = my_list
my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
a, *b, c = my_list
print(a) # 1
print(b) # [2, 3, 4, 5, 6, 7, 8, 9]
print(c) # 10
Источник: Bas Steins