2014-03-02 38 views
-1

我有兩個類,名爲「Pussa」和「Cat」。 Pussa有一個int屬性idPussa,Cat類有兩個屬性,一個「Pussa」列表和一個int catNum。每個班級都有一些方法,使用__init__。所以,我要做到這一點類和方法,在Python中有列表

「(F)現在,我們的貓得到一個‘Pussa’感染。把4個Pussa對象上的所有偶數指數貓上的列表貓。 首先產生20個需要Pussa對象連續編號 然後將Pussa對象的引用複製到相應的貓。「

我已經完成了這段代碼,但我真的不知道該怎麼繼續......我今年剛開始用Python,並且我迷路了。

listPussa = [] 
for x in range(1,21): 
    x = Pussa(x) 
    listPussa.append(x) 

for cat in cats: #cats is a list of 20 cat objects 
    if cat.getcatNum()%2 != 0: 
     for i in range(21): 
      cat.addPussa(i) 
      i = i +1 

Pussa被定義的類:

class Pussa: 
    ''' Class Pussa ''' 
     # (a) Define a private attribute idPussa 

     def __init__(self, idPussa = None): 
       self.__idPussa = idPussa 


     # (b) Define a __str__ method that 
     def __str__(self): 
       self.__idPussa = idPussa 
       if idPussa is None: 
         return "Pussa sin número." 
       else: 
         return "Pussa número = " + idPussa 


     # (c) Define setIdPussa 
     def setIdPussa(self, idPussa): 
       self.__idPussa = idPussa 


     # (c) Define getIdPussa 
     def getIdPussa(self): 
       return self.__idPussa 

和類貓:

class Cat: 
    ''' Class cat ''' 
     # (a) Define the init method with a private attribute called catNum and a list of pusses 
     def __init__(self, catNum = None, listPussa = []): 
       self.__catNum = catNum 
       self.listPussa = listPussa 

     # (b) Define the mixeta method 
     def mixeta(self): 
       if len(self.listPussa) is 0: 
         return "Miau!", self.getcatNum(), "La llista de pusses esta buida" 
       else: 
         for pussa in self.listPussa: 
           return pussa.getIdPussa() 

         return "Miau!", self.getcatNum(), "El nombre total de pusses es ", len(self.listPussa) 



     # (c) Define the setter function for catNum 
     def setcatNum(self, catNum): 
       self.__catNum = catNum 

     # (c) Define the getter function for catNum  
     def getcatNum(self): 
       return self.__catNum 

     # (d) Define a setter for adding a Pussa in the list of pusses 
     def addPussa(self, Pussa): 
       self.listPussa.append(Pussa) 


     # (e) Define the cleanCat method which removes all pusses from the cat, empty the list 
     def cleanCat(self): 
       if len(self.listPussa) is 0: 
         return 
       else: 
         for i in range(len(self.listPussa)): 
           self.listPussa.pop(i) 

每一個幫助和評論是非常有幫助:)

+0

您能否對預期結果做更具體的描述?也許發佈更多的代碼,如類定義... – skamsie

+0

問題描述並沒有說明是否有最多五個偶數貓。如果有更多的指令其餘的說明沒有任何意義。另外,還不清楚是通過引用「Pussa對象」來引用對象還是'idPussa'。 catNum或列表索引是否與偶數條件相關也不明確。 'getcatNum()'的目的不清楚,不妨使用'cat.catNum'。 – Nabla

+0

分配catNum是私人的,所以我想我必須使用getcatNum()否? – Atsuko

回答

3

大概是這樣的?

pussaIndex = 0 
for cat in cats: 
    if cat.getcatNum() % 2 == 0: 
     # add the next four elements from `listPussa` 
     for i in range(4): 
      cat.addPussa(listPussa[pussaIndex]) 
      pussaIndex += 1