我有以下 Python 代碼:
from names import get_first_name, get_last_name
class Person(object):
def __init__(self, first_name=get_first_name(), last_name=get_last_name()):
self.first_name = first_name
self.last_name = last_name
def make_group_of_people(num_people):
people = []
num = 0
while num < num_people:
person = Person(
first_name=get_first_name(),
last_name=get_last_name(),
)
people.append(person)
num = 1
return people
group = make_group_of_people(3)
for person in group:
print(f"***NEW PERSON {group.index(person)}***")
print(person.first_name)
print(person.last_name)
列印出不同的名稱,如下所示:
***NEW PERSON 0***
Christine
Thomas
***NEW PERSON 1***
Orlando
Goff
***NEW PERSON 2***
William
Bedwell
我不明白的是,當我運行這個非常相似的 Python 代碼時:
from names import get_first_name, get_last_name
class Person():
def __init__(self, first_name=get_first_name(), last_name=get_last_name()):
self.first_name = first_name
self.last_name = last_name
def make_group_of_people_2(num_people):
people = []
num = 0
while num < num_people:
person = Person() ### HERE'S WHAT'S DIFFERENT ###
people.append(person)
num = 1
return people
same_named_group = make_group_of_people_2(3)
for person in same_named_group:
print(f"***NEW PERSON {same_named_group.index(person)}***")
print(person.first_name)
print(person.last_name)
我得到這個輸出,表明每個物件都有名字和姓氏:
***NEW PERSON 0***
Michael
Baylock
***NEW PERSON 1***
Michael
Baylock
***NEW PERSON 2***
Michael
Baylock
令我困惑的是,我希望兩段代碼都列印出不同的名稱,因為在這兩種情況下,類的默認值first_name和類的默認值都是names 包的隨機名稱生成器函式的結果,但顯然這不是什么發生。last_namePerson
我看過這個問題,但它并不能完全回答我所看到的。
知道為什么會這樣嗎?這在所有 OOP 語言中是否一致?
uj5u.com熱心網友回復:
問題是你的建構式:
class Person(object):
def __init__(self, first_name=get_first_name(), last_name=get_last_name()):
self.first_name = first_name
self.last_name = last_name
默認引數值在定義函式時(即一次)進行評估,而不是每次呼叫該函式時。(如果你堅持一些登錄,get_first_name()你會看到它在你的代碼的第 2 版中只被呼叫一次。)如果你希望默認值每次都不同,請執行以下操作:
class Person:
def __init__(self, first_name=None, last_name=None):
self.first_name = first_name or get_first_name()
self.last_name = last_name or get_last_name()
以便函式在每次呼叫函式時呼叫get_first_name()并get_last_name()發生,而沒有相應的引數。
uj5u.com熱心網友回復:
您已經為名字和姓氏引數定義了默認值。默認值的意思是如果你不指定它,它會被自動選中。請參閱以下代碼片段:
from names import get_first_name
default = get_first_name()
print(default)
所以當你寫:
person = Person()
將選擇默認值。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/363998.html
