Why are default values shared between objects?
Why are default values shared between objects?
In Python, default values are shared between objects due to the way the language handles function arguments and the instantiation of objects. This behavior is particularly noticeable with mutable default values.
When a function or method in Python is defined, the default arguments are evaluated and created only once, not each time the function is called. This means that if a mutable object (like a list or dictionary) is used as a default value, the same instance of that object will be used in every call of the function where a new argument isn't provided.
For example, consider the following class definition:
class Example:
def __init__(self, my_list=[]):
self.my_list = my_list
Here, my_list is a mutable default argument. If an instance of Example modifies my_list, all instances of Example that use the default list will see this change because they all reference the same list object.
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.