2015-10-28 40 views
0

我還是比較新的Python和一些概念,所以你必須忍受我。試圖從類中的方法打印

我想創建一個動物(在這種情況下是一匹馬),並自動生成一些屬性。在這裏,我嘗試使用get_heights方法生成並應用高度函數。我沒有收到任何錯誤,但是當我將它定義爲獨立函數時,它不會打印出生成的數字。 (課外)

我在Horse_heights.get_heights調用中加了小括號,但後來發現類型錯誤,說get_heights() takes exactly 3 arguments <1 given>。所有幫助表示讚賞,如果我在這裏錯過了一些基本方面,表示歉意。

import random 

class Horse(object): 
    def __init__(self, horse_name): 
     self.horse_name = horse_name 

    def get_heights(self, starting_height, max_height): 
     for sh in range(15): 
      sh1 = random.randint(14, 15) 
      sh3 = str(sh1) 
      self.sh3 = starting_height 
     print starting_height 

     for mh in range(3): 
      mh1 = random.randint(1,2) 
      mh2 = mh1 + sh1 
      mh3 = str(mh2) 
      self.mh3 = max_height 
     print max_height 


Horse_Heights = Horse("Secretariat") 
Horse_Heights.get_heights 

回答

0

正如錯誤說,功能get_height接受3個參數:

def get_heights(self, starting_height, max_height) 

所以,當你調用這個函數插入argments:

import random 

class Horse(object): 
    def __init__(self, horse_name): 
     self.horse_name = horse_name 

    def get_heights(self, starting_height, max_height): 
     for sh in range(15): 
      sh1 = random.randint(14, 15) 
      sh3 = str(sh1) 
      self.sh3 = starting_height 
     print starting_height 

     for mh in range(3): 
      mh1 = random.randint(1,2) 
      mh2 = mh1 + sh1 
      mh3 = str(mh2) 
      self.mh3 = max_height 
     print max_height 


Horse_Heights = Horse("Secretariat") 
Horse_Heights.get_heights(1,15) 
+0

嗯,是的,但隨後沒有使用生成隨機整數以確定高度。我想我必須事先在班級以外定義那些,然後將它們應用到它。 – xGlorify