所以我對 python 相當陌生,我想制作一個程式,從用戶輸入創建一個類的物件,所以我不必制作 10 個空組態檔。我試過這樣,知道它會是假的,但我認為它表明了我的問題。
class Profile():
def __init__(self, weight, height):
self.weight = weight
self.height = height
def create_object():
name = input("What's your name?")
new_weight = input("What's your height?")
new_height = input("What's your weight?")
name = Profile(new_weight, new_height)
return name
如果我現在想創建物件:
>>> create_object()
What's your name? test
What's your height? 23
What's your weight? 33
<__main__.Profile object at 0x000002564D7CFE80>
>>> test()
Traceback (most recent call last):
File "<pyshell#35>", line 1, in <module>
test()
NameError: name 'test' is not defined
或者我應該使用字典,如果是,如何使用?
uj5u.com熱心網友回復:
根據我的經驗,沒有必要專門命名一個類的每個實體。相反,您可以按照一些評論者的建議將每個新物件添加到字典中,如下所示:
object_dict = {}
for i in range(10):
name = input("what's your name")
object_dict[name] = create_object()
這里要注意的不同之處在于我將您的函式的名稱部分移到了create_object()范圍之外。據我所知,沒有“簡單”或“干凈”的方法可以用字串作為用戶輸入在 python 中創建變數(尤其是如果你不熟悉 python)。
如果您所做的不一定需要名稱,并且用戶詳細資訊僅用于資料存盤,那么將名稱保存為類中的屬性會更簡潔,如下所示:
class Profile():
def __init__(self, weight, height, name):
self.weight = weight
self.height = height
self.name = name
然后當您生成組態檔時,只需將它們添加到串列中:
for i in range(10):
object_list.append(create_object)
最后一件事,輸入法總是回傳一個字串。因此,如果您打算使用重量和高度值進行數學運算,則需要將輸入從字串更改為數字,您可以通過將input()呼叫包圍int()起來來完成此操作
name = int(input("What's your name?"))
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/353446.html
