2010-08-14 63 views
12

鑑於蟒類class Student():和列表names = [];然後我想創建多個實例的Student()並將它們添加到列表中names用於存儲類實例的Python列表?

names = [] # For storing the student instances 
class Student(): 
    def __init__(self, score, gender): 
     self.score = score 
     self.gender = gender 

現在我要檢查出所有的男同學的成績,我能做到這樣?

scores = [] 
for i in names: 
    if i.gender == "Male": 
     scores.append(i.score) 

我的問題是:如何創建一個可以(如果可以用任何語句來完成)的列表存儲Student的實例?或者說,當我寫names = []時,我怎麼能說出names中的每個元素都是Student的一個實例,以便我可以使用該元素的屬性,儘管python是弱類型的?我希望我自己清楚;)

我可以寫這樣的:

for i in range(len(names)): 
     student = Student() 
     student = names[i] 
     if student.gender == "Male": 
      # Whatever 

我不這樣想......

+0

響應您的編輯:沒有,因爲你打電話'學生()你不能寫'不帶參數,儘管它需要2.如果你刪除這條線,它會工作。 – sepp2k 2010-08-14 15:47:59

+1

@ sepp2k,是的,參數不符合Student construtor,所以這會導致錯誤。好吧,我認爲我應該考慮我的問題,因爲我現在在表達我的問題時遇到了困難,如果您認爲通過代碼更多,您可能會了解它失敗的位置,但我發佈的內容並不是我的觀點 – ladyfafa 2010-08-14 15:51:38

+0

。 'student = Student()'這一行試圖創建一個新的'Student'實例並將它存儲在變量'student'中。這將失敗,因爲構造函數缺少一些必需的參數。我想你正在試圖宣佈「學生」的類型?你不必在Python中這樣做。它將在運行時爲您解決。還要注意,你可以直接在'names'的元素上用''爲學生名稱:...'進行迭代。 – katrielalex 2010-08-14 18:38:32

回答

11

你嘗試上面的代碼?它應該工作正常。你可以凝結成:

scores = [ student.name for student in names if student.gender == "Male" ] 

請注意,調用列表names是一種誤導,因爲它是Student實例的列表。

您不能將列表定義爲Student實例的列表;這不是Python的工作原理。

您是否在問如何創建名爲names的列表?

names = [ ] 
for (score, gender) in <some-data-source>: 
    names.append(Student(score, gender)) 

這當然是相當於到

names = [ Student(score, gender) for score, gender in <some-data-source> ] 

,並依次

names = [ Student(*row) for row in <some-data-source> ] 

如果你需要做很多處理的每一行,那麼你可以移動的處理轉換爲單獨的功能或使用for循環。

def process_row(row): 
    ... 
    return score, gender 

names = [ Student(*process_row(row)) for row in <some-data-source> ] 

響應您的編輯,我認爲你正在嘗試聲明類型的變量在Python。您寫道:

​​3210

什麼是線student = Student()的目的 - 你想聲明變量student的類型?不要這樣做。下面將做你想要的結果:

for student in students: 
    if student.gender == "Male": 
     # Whatever 

注意幾件事情:

  1. 我們並不需要遍歷range(n)然後每個實例查找在names;遍歷容器的每個元素是for循環的目的。
  2. 您不需要對student是什麼聲明 - 它可以是字符串,布爾值,列表,Student,無論如何。這是動態打字。同樣,students不一定是一個列表;你可以迭代任何可迭代的
  3. 當你編寫student.gender時,Python將得到gender屬性student,或者如果它沒有一個會引發異常。
+1

謝謝你的回答,我看到你的觀點,但我不知道如何表達我的問題,雖然 – ladyfafa 2010-08-14 15:49:01

+0

令人討厭,但濃縮的外觀相當簡潔,在某些情況下,if語句可能包含一堆TODO,這種形式是否可行,可能不那麼直截了當? – ladyfafa 2010-08-14 15:55:58

+0

咦?什麼是'TODO'? – katrielalex 2010-08-14 16:00:07

4

首先python是而不是微弱類型。但是它是動態類型的,所以你不能爲你的列表指定一個元素類型。

但是,這並不妨礙您訪問對象的屬性。這只是正常:

names = [Student(1,"Male"), Student(2,"Female")] 
scores = [] 
for i in names: 
    if i.gender == "Male": 
     scores.append(i.score) 

然而更Python使用列表理解來寫:

names = [Student(1,"Male"), Student(2,"Female")] 
scores = [i.score for i in names if i.gender == "Male"] 
+0

其實,根據大多數定義,我認爲Python *是*弱類型 - 支持重載,隱式類型轉換,多態性...如果這不是「弱類型」,那是什麼?無可否認,這個術語並不意味着什麼。 – katrielalex 2010-08-14 16:01:58

+0

我也想說Python動態類型。 OP只知道相反的:* static * types。看起來* strong *和* weak *對於非常相似的概念來說是相當不好的名字。# – 2010-08-14 16:32:00

+4

編號弱類型表示類型內部沒有太大差異。因此,您可以將字符串變量添加到數字中,就像它也是一個數字一樣。 在Python中你必須知道變量類型。但它可以僅在運行時發現或動態發現。 – Odomontois 2010-08-14 16:33:58

2

我是相當新的OOP,但你要很好地是什麼不能做? name_list是一個類變量,每次創建一個新的Student對象時,它將被添加到Student.name_list。例如說你有一個方法cheat(self)你想要在第三個學生上執行,你可以運行Student.name_list[2].cheat()。代碼:

class Student(): 
    name_list = [] 
    def __init__(self, score, gender): 
     Student.name_list.append(self) 
     self.score = score 
     self.gender = gender 

    #this is just for output formatting 
    def __str__(self): 
     return "Score: {} || Gender: {}".format(self.score, self.gender) 

#again for output formatting 
def update(): print([str(student) for student in Student.name_list]) 

update() 
Student(42, "female") 
update() 
Student(23, "male") 
update() 
Student(63, "male") 
Student(763, "female") 
Student("over 9000", "neutral") 
update() 

輸出:

[] 
['Score: 42 || Gender: female'] 
['Score: 42 || Gender: female', 'Score: 23 || Gender: male'] 
['Score: 42 || Gender: female', 'Score: 23 || Gender: male', 'Score: 63 || Gender: male', 'Score: 763 || Gender: female', 'Score: over 9000 || Gender: neutral'] 
相關問題