为什么要为第二个实例调用保留默认参数?
Why are default arguments retained for the second instance call?
当我执行下面的代码时,第一次打印名称值时它会打印正确的名称,即“John”。
但是当我创建第二个空实例时,它仍然打印名称“John”。
预期输出应该是,它将仅打印“空名称”,因为 friend_2 使用新的空实例。
class User:
def __init__(self,name ="Empty name"):
self.__name = name
def get_name(self):
return self.__name
def set_name(self,word):
self.__name = word
class Friend:
def __init__(self,user = User()):
self.__user = user
def get_user(self):
return self.__user.get_name()
def set_n(self,name):
self.__user.set_name(name)
friend_1 = Friend()
# Only friendd_1 instance is being set to name John
friend_1.set_n("John")
name_1 = friend_1.get_user() # expected as we set John to friend_1 instance
friend_2 = Friend() # use new User empty instance
name_2 = friend_2.get_user() # This value is also John, but it should print "Empty value" as we are using default argument.
如评论中所述,可变默认参数是一个常见问题。
class Friend:
def __init__(self, user = None):
# Default to None instead and then create the object during initialization
self.__user = user if user else User()
当我执行下面的代码时,第一次打印名称值时它会打印正确的名称,即“John”。
但是当我创建第二个空实例时,它仍然打印名称“John”。 预期输出应该是,它将仅打印“空名称”,因为 friend_2 使用新的空实例。
class User:
def __init__(self,name ="Empty name"):
self.__name = name
def get_name(self):
return self.__name
def set_name(self,word):
self.__name = word
class Friend:
def __init__(self,user = User()):
self.__user = user
def get_user(self):
return self.__user.get_name()
def set_n(self,name):
self.__user.set_name(name)
friend_1 = Friend()
# Only friendd_1 instance is being set to name John
friend_1.set_n("John")
name_1 = friend_1.get_user() # expected as we set John to friend_1 instance
friend_2 = Friend() # use new User empty instance
name_2 = friend_2.get_user() # This value is also John, but it should print "Empty value" as we are using default argument.
如评论中所述,可变默认参数是一个常见问题。
class Friend:
def __init__(self, user = None):
# Default to None instead and then create the object during initialization
self.__user = user if user else User()